Pull API request into nested struct

Issue

I’m currently pulling an API response into a struct.

I’m fine with a normal response of say:

  [ 
    {"date":"2021-10-04","user":"Test","url":"Anonymous"]},
    {"date":"2021-10-04","user":"Test","url":"Anonymous"]},
    {"date":"2021-10-04","user":"Test","url":"Anonymous"]},
  ]

However when I get data like this:

  "urls": [
    {"date":"2021-10-04","user":"Test","url":"Anonymous"]},
    {"date":"2021-10-04","user":"Test","url":"Anonymous"]},
    {"date":"2021-10-04","user":"Test","url":"Anonymous"]},
  ]

I cant seem to parse it to the struct.

It seems like a stupid question as its basically the same.

Here is what I am doing:

   type urls struct {
    Urls struct {
        Date   string `json:"date"`
        User   string `json:"user"`
        Urls   string `json:"urls"`
    } `json:"urls"`
   }

   type url []urls

and within the function:

   resp, err := http.Get("https://url")
   if err != nil {
        fmt.Println("No response from request")
   }
   defer resp.Body.Close()
   body, err := ioutil.ReadAll(resp.Body) // response body is []byte
   var u url
   _ = json.Unmarshal(body, &u)

Unfortunately this isnt working and u is empty.

With the first response I can have a struct like this and it works fine:

  type urls struct {
       Date   string `json:"date"`
       User   string `json:"user"`
       Urls   string `json:"urls"`
  }

Solution

I think what I’m trying to say is a combination of the above and plus a little bit of my experience.

  1. Your Urls field is an array in JSON, but not in the struct you declared.
  2. You should not ignore the error returned by json.Unmarshal(body, &u) .
  3. The Json you posted is not grammatically correct.
    I modified your Json string slightly, it could be:
{
"urls": [
    {"date":"2021-10-04","user":"Test","url":"Anonymous"},
    {"date":"2021-10-04","user":"Test","url":"Anonymous"},
    {"date":"2021-10-04","user":"Test","url":"Anonymous"}
  ]
}

And to Go struct should be:

type URL struct {
    SubURLs []struct {
        Date string `json:"date"`
        User string `json:"user"`
        URL  string `json:"url"`
    } `json:"urls"`
}

Next, I introduce you to one possible way when you are dealing with JSON to Go structs:
You can paste your Json on this website, and then you can get its corresponding Go structure, and you can also correct your Json by the way.

Answered By – kocoler

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.