为了账号安全,请及时绑定邮箱和手机立即绑定

不能使用“encoding/json”覆盖鹰(类型接口 {})

不能使用“encoding/json”覆盖鹰(类型接口 {})

Go
炎炎设计 2023-06-12 14:36:13
我有以下代码,我想遍历所有元素或访问一个元素,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


查看完整回答
反对 回复 2023-06-12
  • 1 回答
  • 0 关注
  • 112 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信