我有以下代码,我想遍历所有元素或访问一个元素,birds["eagle"["quote"][2]但我无法弄清楚package mainimport ( "fmt" "encoding/json")func main() { birdJson := `{"birds": {"pigeon": {"quotes": "love the pigeons"}, "eagle": {"quotes": ["bird of prey", "soar like an eagle", "eagle has no fear"]}}}` var result map[string]interface{} json.Unmarshal([]byte(birdJson), &result) birds := result["birds"].(map[string]interface{}) fmt.Printf("%v\n",birds) eagle := birds["eagle"] for key, value := range eagle { fmt.Println(key, value.(string)) }}
1 回答
临摹微笑
TA贡献1982条经验 获得超2个赞
有几个问题:
eagle := birds["eagle"] //eagle is of type interface{}
所以把它投到地图上:
eagle := birds["eagle"].(map[string]interface{})
现在你可以迭代它了:
for key, value := range eagle {
for _, e := range value.([]interface{}){
fmt.Println(key, e.(string))
}
}
值又是这里的接口。所以首先转换为 []interface{} 然后转换为字符串。
这是完整的工作代码: https ://play.golang.org/p/Bdnwit1wBYh
- 1 回答
- 0 关注
- 147 浏览
添加回答
举报
0/150
提交
取消