我需要将 json 字符串转换为 map 。这是我的 go 程序。
package main
import (
"encoding/json"
"fmt"
)
func main() {
str := `{
"Bangalore_City": "35_Temperature",
"NewYork_City": "31_Temperature",
"Copenhagen_City": "29_Temperature",
"hobbies" : {
"name" : "username"
}
}`
var m map[string]interface{}
json.Unmarshal([]byte(str), &m)
fmt.Println(m["hobbies"]["name"])
}
如果我使用此代码,则会出现以下错误。
get.go:26:26: invalid operation: m["hobbies"]["name"] (type interface {} does not support indexing)
请任何人帮助解决这个问题。提前致谢
最佳答案
您还需要在 m["hobbies"]
上键入 assert 才能成为 map[string]interface{}
,
喜欢this :
fmt.Println(m["hobbies"].(map[string]interface{})["name"])
您也可以check that it has the expected type before accessing the name
关于go - 如何使用json marshal获取 map 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52696496/