3

I am consuming an API who's response for a particular field is sometimes and object and sometimes and array of object.

I created a struct to unmarshall the json response and it works great. However, in the instances where the json response has an array of objects, obviously the unmarshalling fails. How can I deal with this situation in Go?

Single Response:
{
    "net": {
                "comment": {
                    "line": {
                        "$": "This space is statically assigned",
                        "@number": "0"
                    }
                }
            }
}


Array Response:
{
    "net": {
                "comment": {
                    "line": [
                        {
                            "$": "All abuse issues will only be responded to by the Abuse",
                            "@number": "0"
                        },
                        {
                            "$": "Team through the contact info found on handle ABUSE223-ARIN",
                            "@number": "1"
                        }
                    ]
                }
            }
}

I thought about creating 2 versions of the struct and then somehow determining which instance I got back, but this feels quite wasteful. I have also tried unmarshalling into map[string]instance{} but I got a bit lost and wasn't sure if I was headed down the right path.

Any advice would be appreciated.

Techie210
  • 55
  • 1
  • 4
  • 7
    see here: http://stackoverflow.com/questions/32346117/unmarshalling-a-json-that-may-or-may-not-return-an-array and http://stackoverflow.com/questions/33569210/go-json-unmarshal-options – JimB Nov 10 '15 at 02:52
  • Thanks again @JimB I used http://stackoverflow.com/questions/32346117/unmarshalling-a-json-that-may-or-may-not-return-an-array to figure this out. Took me some time to get my head wrapped around it, but there you go. – Techie210 Nov 11 '15 at 19:54

1 Answers1

2

Have you tried unmarshall into map[string]interface{}?

    type Net struct{
        Comment map[string]interface{} `json:"comment"`
    }

Then Comment["line"] value is possible array or object.

  • Thanks all. Lê Ngọc Thạch this is the simplest and most elegant solution. Thanks much! – Techie210 Nov 11 '15 at 02:30
  • This does not seem to work for the array case. Its only picking up single objects. How do you iterate through an array of objects using this method? – Ray Jun 25 '21 at 15:28