hello world hello world - 3 years ago 244
JSON Question

How to access key and value from json in golang?

I have a struct

type Order struct {
ID string `json:"id"`
CustomerMobile string `json:"customerMobile"`
CustomerName string `json:"customerName"`
}


and the json data:

[{"Key":"S001", "Record":{"id":"SOO1","customerMobile":"12344566","customerName":"John"}}]


How can i access customerMobile key from the above json object?

I have done some research in Google and i found the below solution, but its not working when i apply to my above requirement. Its working with simple json format.

jsonByteArray := []byte(jsondata)
json.Unmarshal(jsonByteArray, &order)

Answer Source

You need to unmarshal into something that represents the entire JSON object. Your Order struct defines part of it, so just define the rest of it, as follows:

package main

import (
    "encoding/json"
    "fmt"
)

type Order struct {
    ID             string `json:"id"`
    CustomerMobile string `json:"customerMobile"`
    CustomerName   string `json:"customerName"`
}

type Thing struct {
    Key    string `json:"Key"`
    Record Order  `json:"Record"`
}

func main() {
    jsonByteArray := []byte(`[{"Key":"S001", "Record":{"id":"SOO1","customerMobile":"12344566","customerName":"John"}}]`)
    var things []Thing
    err := json.Unmarshal(jsonByteArray, &things)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", things)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download