我有以下代碼,我想遍歷所有元素或訪問一個元素,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條經(jīng)驗 獲得超2個贊
有幾個問題:
eagle := birds["eagle"] //eagle is of type interface{}
所以把它投到地圖上:
eagle := birds["eagle"].(map[string]interface{})
現(xiàn)在你可以迭代它了:
for key, value := range eagle {
for _, e := range value.([]interface{}){
fmt.Println(key, e.(string))
}
}
值又是這里的接口。所以首先轉(zhuǎn)換為 []interface{} 然后轉(zhuǎn)換為字符串。
這是完整的工作代碼: https ://play.golang.org/p/Bdnwit1wBYh
- 1 回答
- 0 關(guān)注
- 180 瀏覽
添加回答
舉報
0/150
提交
取消