az rnd
az rnd

Reputation: 883

How to get map value using json marshal

I need to convert json string to map. Here is my go program.

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

If I use this code I am getting the below error.

get.go:26:26: invalid operation: m["hobbies"]["name"] (type interface {} does not support indexing)

Please anyone help to fix this issue. Thanks in advance

Upvotes: 1

Views: 3303

Answers (2)

colega
colega

Reputation: 151

You need to type assert on m["hobbies"] to be a map[string]interface{} too, like this:

fmt.Println(m["hobbies"].(map[string]interface{})["name"])

You can also check that it has the expected type before accessing the name

Upvotes: 1

白栋天
白栋天

Reputation: 172

I use jsoniter(github.com/json-iterator/go) which is very fast and compatible with golang json package to do this:

the code could be like this

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

Or u can write code like this when using 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"])
}

Upvotes: 1

Related Questions