Home > Software design >  How do I parse JSON in Go where array elements have more than one type?
How do I parse JSON in Go where array elements have more than one type?

Time:09-21

How can I parse a JSON response from https://api.twitchinsights.net/v1/bots/online to an array in Go and iterate over every entry?

I dont understand the struct because there are no keys only values...

Can anyone please help and explain how this works?

I've mapped it but then I get something like

map[_total:216 bots:[[anotherttvviewer 67063 1.632071051e 09] [defb 26097 1.632071051e 09] [commanderroot 17531 1.632071048e 09] [apparentlyher 16774 1.63207105e 09]... 

But I cant iterate over the map.

CodePudding user response:

Because the API you're working with returns data where it could be a string or a number (in the array of arrays property bots), you'll need to use []interface{} as the type for each element of that array because the empty interface (https://tour.golang.org/methods/14) works for any type at run time.

type response struct {
    Bots  [][]interface{} `json:"bots"`
    Total int             `json:"_total"`
}

Then, as you iterate through each item in the slice, you can check its type using reflection.

It would be ideal for the API to return data in a schema where every JSON array element has the same JSON type as every other element in its array. This will be easier to parse, especially using statically typed languages like Go.

For example, the API could return data like:

{
  "bots": [
    {
      "stringProp": "value1",
      "numberProps": [
        1,
        2
      ]
    }
  ],
  "_total": 1
}

Then, you could write a struct representing the API response without using the empty interface:

type bot struct {
    StringProp  string    `json:"stringProp"`
    NumberProps []float64 `json:"numberProps"`
}

type response struct {
    Bots  []bot `json:"bots"`
    Total int   `json:"_total"`
}

But sometimes you're not in control of the API you're working with, so you need to be willing to parse the data from the response in a more dynamic way. If you do have control of the API, you should consider returning the data this way instead.

  • Related