【问题标题】:Golang print map inside map generated by json.NewDecoderjson.NewDecoder生成的地图内的Golang打印地图
【发布时间】:2017-06-12 15:10:33
【问题描述】:

我正在使用the answer here 从 api 获取一些 json:

package main

import (
   "encoding/json"
   "fmt"
   "log"
   "net/http"
)

func main() {
   resp, err := http.Get("http://api.openweathermap.org/data/2.5/forecast?id=524901&appid=1234")
   if err != nil {
      log.Fatal(err)
   }
   var generic map[string]interface{}
   err = json.NewDecoder(resp.Body).Decode(&generic)
   if err != nil {
      log.Fatal(err)
   }
   fmt.Println(generic)
}

它正在工作,我有一个存储在generic 变量中的 json 映射。

当我打印时:

fmt.Println(generic["city"])

我回来了:

map[id:524901 name:Moscow coord:map[lon:37.615555 lat:55.75222] country:RU population:0 sys:map[population:0]]

现在我想访问城市名称。我正在尝试以下方法:

fmt.Println(generic["city"]["name"])

我得到错误:

muxTest/router.go:30: 无效操作:generic["city"]["name"] (type interface {} 不支持索引)

还尝试了generic["city"].name,但没有成功。

如何访问城市名称值?

【问题讨论】:

    标签: go


    【解决方案1】:

    您需要将map[string]interface{}interface{} 转换为更有用的东西。在这种情况下,map[string]interface{} 再次出现,因为city 本身就是一张地图。您无法将其转换为其他任何内容,因为 coord 也是地图,因此无法将城市转换为 map[string]string

    https://play.golang.org/p/bGsYLnSAK4

    【讨论】:

      猜你喜欢
      • 2012-08-19
      • 2016-03-18
      • 2015-10-05
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      • 2022-01-08
      • 1970-01-01
      • 2021-04-18
      相关资源
      最近更新 更多