【问题标题】:How to get map value using json marshal如何使用 json marshal 获取地图值
【发布时间】:2018-10-08 06:25:39
【问题描述】:

我需要将 json 字符串转换为映射。这是我的围棋程序。

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)

请任何人帮助解决此问题。提前致谢

【问题讨论】:

  • 这是因为键 hobbies 返回 interface{} 类型,而不是 map[string]string,如果您的数据具有固定模式,那么我建议您创建一个结构并解组!

标签: go


【解决方案1】:

您也需要在 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

【讨论】:

    【解决方案2】:

    我使用 jsoniter(github.com/json-iterator/go) 非常快并且与 golang json 包兼容:

    代码可能是这样的

    jsoniter.Get([]byte(str), "hobbies", "name")
    

    或者你可以在使用 golang json 时编写这样的代码:

    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)
        // since m["hobbies"] is an interface type, u can't use it 
        // as a map[string]string type, so add a ".(map[string]string)"
        // to change this interface, then u can get the value of key "name"
        fmt.Println(m["hobbies"].(map[string]string)["name"])
    }
    

    【讨论】:

    • 这不是他实际问题的解决方案,他正在摸索 Golang 中数据类型的基础知识,并且建议一个库实际上对此没有帮助。
    • 你是对的,因为我认为jsoniter比golang json好,所以我推荐这个lib,对不起。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    相关资源
    最近更新 更多