英文:
Iterating and getting values from a map
问题
我有一些JSON数据,我已经将其解组成一个名为data_json的映射。它包含几百个项。
使用以下代码,我可以成功地从映射中获取一个项的"dn"值,但是我不知道如何迭代整个结构以获取映射中所有项的"dn"值。
objects := data_json["data"].([]interface{})
first := objects[0].(map[string]interface{})
fmt.Println(first["dn"])
我尝试了这种方法,但是我对如何构建键和值感到困惑。
for v, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}
英文:
I have some JSON data that I've un-marshalled into a map called data_json. It contains several hundred items.
Using the following code I can successfully retrieve the value of "dn" for one of the items in the map, however I'm struggling how to iterate over the entire structure to get the value for "dn" for all items in the map.
objects := data_json["data"].([]interface{})
first := objects[0].(map[string]interface{})
fmt.Println(first["dn"])
I've tried this type of approach but I'm confused as to how I should construct keys and values.
for v, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}
答案1
得分: 1
如果你的意思是所有项目都是objects
,你可以这样做:
func printAllDataDn(data_json map[string]interface{}) {
objects := data_json["data"].([]interface{})
for _, v := range objects {
item := v.(map[string]interface{})
fmt.Println(item["dn"])
}
}
英文:
If you means all items is objects
, you will do that, like this:
func printAllDataDn(data_json map[string]interface{}) {
objects := data_json["data"].([]interface{})
for _, v := range objects {
item := v.(map[string]interface{})
fmt.Println(item["dn"])
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论