go - 如何使用json marshal获取 map 值

标签 go

我需要将 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/

相关文章:

http - 在 Golang 中处理并发 HTTP 请求

mongodb - 在出现错误的情况下重新创建 mgo session (读取 tcp 127.0.0.1 :46954->127. 0.0.1:27017: i/o 超时)

go - 从HEAD请求输出Content-Type

go - 是否应该将 go.sum 文件 checkin 到 git 存储库中?

javascript - 保护 "back-end" Angular 源文件

go - 如何在 Golang 中将 ast.TypeSpec 断言为 int 类型?

google-app-engine - 错误 : (gcloud. app.deploy) INVALID_ARGUMENT:无法解析源

http - golang http服务器处理程序和指针问题

GoLang printf 什么都不显示,即使在使用 time.Sleep 之后

mysql - GoLang 的配置返回 "non-name"错误