英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论