简体   繁体   中英

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)

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

Give a try to this: https://play.golang.org/p/pruDx70SjW

package main

import (
    "encoding/json"
    "fmt"
)

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

type Orders struct {
    Key    string
    Record Order
}

type Order struct {
    ID             string
    CustomerMobile string
    CustomerName   string
}

func main() {
    var orders []Orders
    if err := json.Unmarshal([]byte(data), &orders); err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", orders)
}

In this case, I am omitting the struct tags

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM