在Python中将任何JSON转换为标准dict的golang相当于什么? [英] What's the golang equivalent of converting any JSON to standard dict in Python?
问题描述
在Python中,您可以执行以下操作:
In Python you can do something like this:
r = requests.get("http://wikidata.org/w/api.php", params=params)
data = r.json()
而现在数据
是一个dict或哈希表(也是我不需要预先定义dict的结构),我可以通过做数据[实体],数据[实体] [Q12]等。
And now data
is a dict or hash table (also, I did not need to define beforehand the structure of the dict), and I can access values of keys by doing data["entities"], data["entities"]["Q12"], etc.
我如何在golang?到目前为止,我有这样的:
How would I do this in golang? So far I have this:
resp, err := http.Get("http://wikidata.org/w/api.php?"+v.Encode())
if err != nil {
// handle error
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
var data interface{}
decodeErr := decoder.Decode(&data)
if decodeErr != nil {
// handle error
}
fmt.Println(data["entities"], data["entities"]["Q"+id])
哪个给我编译错误:无效操作:data [entities](index { )
那么应该是什么类型的 var data
我需要事先定义JSON的结构,还是可以处理任何JSON文件/流而不修改代码?
So what type should var data
be? And do I need to define a structure to the JSON beforehand or is it possible to handle any JSON file/stream without modifying the code?
推荐答案
如果您想要一个字典,请使用Go类型 map [string] interface {}
(这是一个地图
与 string
键和任何类型的值):
If you want a dictionary, use the Go type map[string]interface{}
(which is a map
with string
keys and values of any type):
var data map[string]interface{}
然后你可以参考它的元素,如:
And then you can refer to its elements like:
data["entities"]
看到这个例子:
s := `{"text":"I'm a text.","number":1234,"floats":[1.1,2.2,3.3],
"innermap":{"foo":1,"bar":2}}`
var data map[string]interface{}
err := json.Unmarshal([]byte(s), &data)
if err != nil {
panic(err)
}
fmt.Println("text =", data["text"])
fmt.Println("number =", data["number"])
fmt.Println("floats =", data["floats"])
fmt.Println("innermap =", data["innermap"])
innermap, ok := data["innermap"].(map[string]interface{})
if !ok {
panic("inner map is not a map!")
}
fmt.Println("innermap.foo =", innermap["foo"])
fmt.Println("innermap.bar =", innermap["bar"])
fmt.Println("The whole map:", data)
输出:
text = I'm a text.
number = 1234
floats = [1.1 2.2 3.3]
innermap = map[foo:1 bar:2]
innermap.foo = 1
innermap.bar = 2
The whole map: map[text:I'm a text. number:1234 floats:[1.1 2.2 3.3]
innermap:map[foo:1 bar:2]]
尝试在 Go Playground 。
注意:
基本上,如果您的地图是多层次的(地图$在上述示例中,当您访问内部地图时,c $ c>包含另一个
地图
),如innermap
,您可以使用类型声明将其作为另一个地图:
Basically if your map is multi-level (the map
contains another map
) like the "innermap"
in the above example, when you access the inner map, you can use Type assertion to have it as another map:
innermap, ok := data["innermap"].(map[string]interface{})
// If ok, innermap is of type map[string]interface{}
// and you can refer to its elements.
这篇关于在Python中将任何JSON转换为标准dict的golang相当于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!