我想检索所有ID以及索引值。
{
"results": [
{
"ID": "3b72"
},
{
"ID": "d953b1"
},
{
"ID": "8eac"
},
{
"ID": "00b4c"
},
{
"ID": "22360"
}
],
"index": 10
}
我尝试了以下操作,但没有成功(我在golang中是一个新手):
var result map[string]interface{}
json.Unmarshal([]byte(body), &result)
ids:= result["results"].(map[string]interface{})
for key, value := range ids{
fmt.Println(key, value.(string))
}
根据您的json字符串,需要解决的问题很少。首先,result["results"]
必须将属性强制转换为[]interface{}
因为results
保存数组数据。
ids := result["results"].([]interface{})
然后,在的每次迭代中ids
,需要将变量value
(类型为interface{}
)强制转换为map[string]interface{}
,这样我们就可以访问ID
property以获取其值。
for index, value := range ids {
valueMap := value.(map[string]interface{})
fmt.Println(index, valueMap["ID"])
}
工作示例:https : //play.golang.org/p/Pxq6u7q-NAK
按照@Andrejs的答案,如果您的JSON结构是固定的,那么在结果上使用定义良好的结构会更好(请参阅@danopz的答案)。它具有更好的性能,并且花费更少的精力与孩子互动。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句