Parse JSON into nested structs

Issue

type APIResponse struct {
    Results []Result    `json:"results,omitempty"`
    Paging  Paging
}
type Result struct {
    Id string `json:"id"`,
    Name string `json:"name"`,
}
type Paging struct {
    Count    int    `json:"count"`
    Previous string `json:"previous"`
    Next     string `json:"next"`
}

func  Get(ctx context.Context) APIResponse[T] {
    results := APIResponse{}
    rc, Err := r.doRequest(ctx, req)
    if rc != nil {
        defer rc.Close()
    }
    err = json.NewDecoder(rc).Decode(&results)
    return results
}

The Sample JSON looks like this:

{
    "count": 70,
    "next": "https://api?page=2",
    "previous": null,
    "results": [
        {
            "id": 588,
            "name": "Tesco",
            }...

and I want it decoded into a struct of the form APIResponse, where the pagination element is a substruct, like the results is. However, in the sample JSON, the pagination aspect does not have a parent json tag. How can it be decoded into it’s own separate struct?

Currently, if I lift Count,Next, and Previous into the APIResponse, they appear, but they don’t appear when they’re a substruct.

Solution

Embed your Paging struct directly into APIResponse like:

type APIResponse struct {
    Results []Result    `json:"results,omitempty"`
    Paging
}
type Result struct {
    Id string `json:"id"`,
    Name string `json:"name"`,
}
type Paging struct {
    Count    int    `json:"count"`
    Previous string `json:"previous"`
    Next     string `json:"next"`
}

This way it will work as it defined in this structure. You can access its fields two ways:

  1. Directly:
    APIResponse.Count
  2. Indirect:
    APIResponse.Paging.Count

Answered By – Fenistil

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.