我有以下代码,我想覆盖所有元素或访问一个元素,例如birds["eagle"["quote"][2],但我无法弄清楚

package main

import (
    "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))
    }
}

The Go Playground

最佳答案

有几个问题:

eagle := birds["eagle"] //eagle is of type interface{}

因此将其投射到 map 中:
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

10-07 14:27