Articles Code About

Dealing with Crappy JSON in Go

Over the past few days I've started to dabble in Go. So far, I'm really enjoying the language. And given the adoption and big organizations using it in production, I'm comfortable with investing some time into getting familiar with it.

One thing I noticed when reading about JSON with Go, is that most of examples are under the assumption that the JSON feeds you will be dealing with are actually well designed. Unfortunately it seems like a lot of the feeds I end up needing to deal with are of poor design. So I thought I would put together some examples showing how to read JSON data without having a predefined struct.

One characteristic of the JSON feeds I run into are a list of objects, yet all of the Go examples out there are under the assumption that you are reading an object itself. Below is a sample showing how to return a slice of JSON objects.

data := GetSomeJSON()  
objects := data.([]interface{})  

From here, if you have defined a type for the object you are expecting you can cast say the first entry of the slice to your object:

myObject := objects[0].(MyType)  

In some cases, the lists returned by the feeds are not always consistent in their values. For example, the list may contain 2 objects that meet my expectation, but in some cases one of them will be a string. It could look something like this:

[
    {
        "type": 1
        "value": "some value"
    },
    "error 1"
]

Yeah, that's annoying. Similar to instanceof in python, Go has what is called type assertions. To check the above, I would check to see if the list entry is of the type string:

switch x := objects[1].(type) {  
    case string:
        // some code
    case default:
        // some other code
}

You can also use TypeOf in reflect.

You can learn more by reading up on Go interfaces.