迭代并从映射中获取值

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

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"])
	}
}

huangapple
  • 本文由 发表于 2014年12月20日 09:46:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/27576185.html
匿名

发表评论

匿名网友

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

确定