Golang :How to parse/unmarshal/decode a json array API response?

Struct declarations can be nested inside one another.

The following struct should be convertable from that json:

type resp struct {
    Items []struct {
        Project string `json:"project"`
        Article string `json:"article"`
        Granularity string `json:"granularity"`
        Timestamp string `json:"timestamp"`
        Access string `json:"access"`
        Agent string `json:"agent"`
        Views int `json:"views"`
    } `json:"items"`
}

I generated that with json-to-go, which is a great time saver when working with JSON APIs.


Your solution:

data := struct {
    Items []struct {
        Project string `json:"project"`
        Article string `json:"article"`
        Granularity string `json:"granularity"`
        Timestamp string `json:"timestamp"`
        Access string `json:"access"`
        Agent string `json:"agent"`
        Views int `json:"views"`
    } `json:"items"`
}{}

// you don't need to convert body to []byte, ReadAll returns []byte

err := json.Unmarshal(body, &data)
if err != nil { // don't forget handle errors
}