1

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)

2 Answers 2

4

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

how to access the value of customerMobile key
@helloworld things[0].Record.CustomerMobile will give you the Key. Details - play.golang.org/p/kBX6jqdSA-
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.