Golang打印由json.NewDecoder生成的嵌套map。

huangapple go评论75阅读模式
英文:

Golang print map inside map generated by json.NewDecoder

问题

我正在使用这里的答案从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: invalid operation: generic["city"]["name"] (type interface {} does not support indexing)

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

如何访问城市名称的值?

英文:

I'm using the answer here to fetch some json from an api:

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)
}

It's working, I have a map of the json stored in the generic variable.

When I print with:

fmt.Println(generic["city"])

I get back:

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

Now I want to access the city name. I'm trying the following:

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

And I get error:

> muxTest/router.go:30: invalid operation: generic["city"]["name"] (type
> interface {} does not support indexing)

Also tried generic["city"].name which didn't work.

How can I access the city name value?

答案1

得分: 1

你需要将map[string]interface{}interface{}转换为更有用的类型。在这种情况下,再次转换为map[string]interface{},因为city本身就是一个map。你无法将其转换为其他类型,因为coord也是一个map,所以无法将city转换为map[string]string

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

英文:

You need to cast the interface{} of your map[string]interface{} to something more useful. In this case a map[string]interface{} again since city is itself a map. You can't convert it to anything else because the coord is a map too, so converting city to a map[string]string isn't possible.

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

huangapple
  • 本文由 发表于 2017年1月27日 08:39:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/41885456.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定