Custom Search

Tuesday, October 25, 2016

Go Golang decode unmarshal json string to map

package main

import (
"encoding/json"
"fmt"
"reflect"
)



func main() {

str := `{"name": "sam",
             "age": 30,
             "details": {"salary":10000}
            }`

/*This means the key of map named data is a string but the value can be anything*/
/*An interface{} type is a type that could be any value. It’s like Object in Java.*/
var data map[string]interface{}

fmt.Println("==type of str==", reflect.TypeOf(str))
fmt.Println("==str==", str)

/*json.Unmarshal is used when the input is []byte*/
/*stores the decoded result in map named data*/
fmt.Println("==[]byte(str)==", []byte(str))
err := json.Unmarshal([]byte(str), &data)

if err != nil {
panic(err)
}

fmt.Printf("==data==%#v \n\n", data)
fmt.Println("==name== ", data["name"])

/*Type assertions, check type of data["details"]
 https://tour.golang.org/methods/15*/
details, ok := data["details"].(map[string]interface{})
if ok {
fmt.Println("==salary== ", details["salary"])
}
}