Sometimes JSON sometimes massages an object

I use an API for which the answer for a certain field is sometimes an object, and sometimes an array of an object.

I created a framework to parse the json answer and it works fine. However, in cases where the json response has an array of objects, it is obvious that non-marshalling fails. How can I handle 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 structure, and then somehow determined which instance I was back in, but that seems pretty wasteful. I also tried unmarshalling in map [string] instance {}, but I got a little lost and was not sure that I was headed the right way.

Any advice would be appreciated.

+3
source share
1 answer

unmarshall [string] {}?

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

Then Comment [ "line" ] value - .

+2

Source: https://habr.com/ru/post/1615155/


All Articles