Home > Back-end >  How can I get this type of data in Go lang?
How can I get this type of data in Go lang?

Time:03-20

This is API response data, looks like this.

{   
    "result":1,
    "message":"",
    "pds": [
                {
                    "state":"Y",
                    "code":13,
                    "name":"AAA",
                    "price":39900,
                },
                {
                    "state":"Y",
                    "code":12,
                    "name":"BBB",
                    "price":38000,
                }
            ],
    "request":
            {
                "op":"new",
            }
}

How can I get this data in Go lang? I tried json.Unmarshall and get with map[string]interface{} but it looks like I used the wrong type to get the data. Should I use structure??

CodePudding user response:

You need to create a struct to handle this properly if you don't want the json.Unmarshall output to be a map[string]interface{}.

If you map this JSON object to a Go struct you find the following structure:

type APIResponse struct {
    Result  int    `json:"result"`
    Message string `json:"message"`
    Pds     []struct {
        State string     `json:"state"`
        Code  int        `json:"code"`
        Name  string     `json:"name"`
        Price float64    `json:"price"`
    } `json:"pds"`
    Request struct {
        Op string `json:"op"`
    } `json:"request"`
}

You also can find a great tool to convert JSON objects to Go structs here

CodePudding user response:

if you don`t want to use the native json.Unmarshall ,

Here's a good option to use the package go-simplejson

  •  Tags:  
  • go
  • Related