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

Issue

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

Solution

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

Answered By – Raphael Salomao

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.