如何使用JSON元帅获取地图值

时间:2018-10-08 06:25:40

标签: go

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

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)

请任何人帮助解决此问题。预先感谢

2 个答案:

答案 0 :(得分:1)

我使用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"])
}

答案 1 :(得分:0)

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