不能在带“的eagle(类型接口{})上范围;编码/json“;

不能在带“的eagle(类型接口{})上范围;编码/json“;,json,go,Json,Go,我有下面的代码,我想覆盖所有元素,或者访问一个元素,比如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 a

我有下面的代码,我想覆盖所有元素,或者访问一个元素,比如
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))
    }
}
有几个问题:

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))
        }
    }
值也是这里的接口。所以首先转换为[]接口{},然后转换为字符串。
以下是完整的工作代码:

你们必须像对待鸟类一样使用typeassert。谢谢大家,我不习惯
接口{}
这件事,它现在有意义了。