'How can I get this type of data in Go lang?

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??

go


Solution 1:[1]

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

Solution 2:[2]

If you don't want to use the native json.Unmarshall, here's a good option to use the package go-simplejson.

Documentation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Raphael Salomao
Solution 2 Tyler2P