将JSON解析为map。

huangapple go评论86阅读模式
英文:

Unmarshal JSON into map

问题

我有一个非常简单的JSON文件,类似于这样,但有成千上万个字符串:

{"fruits":["apple","banana","cherry","date"]}

我想将水果加载到一个

map[string]interface{}

中。最好的方法是什么?有没有一种方法可以不需要遍历每个元素并使用循环将其插入到地图中?

英文:

I have a really simple JSON file, something like this, but with thousands of strings:

{"fruits":["apple","banana","cherry","date"]}

and I want to load the fruits into a

map[string]interface{}

What is the best method? Is there a way where I don't need to iterate over each element and insert into the map using a loop?

答案1

得分: 10

这是一个示例,演示如何在没有任何结构的情况下将数据解组为字符串列表。

package main

import "fmt"
import "encoding/json"

func main() {
    src_json := []byte(`{"fruits":["apple","banana","cherry","date"]}`)
    var m map[string][]string
    err := json.Unmarshal(src_json, &m)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%v", m["fruits"][0]) //apple
}

或者,您可以使用map[string][]interface{}代替字符串列表。

英文:

here is example how you can Unmarshal to string list without any struct.

package main
 
import "fmt"
import "encoding/json"

func main() {
	src_json := []byte(`{"fruits":["apple","banana","cherry","date"]}`)
	var m map[string][]string
	err := json.Unmarshal(src_json, &m)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%v", m["fruits"][0]) //apple
 }

Or instead of String list you can use
map[string][]interface{}

huangapple
  • 本文由 发表于 2017年7月14日 17:56:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/45100021.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定