Dynamic JSON Parsing

Almost always when writing a REST endpoint you will know beforehand the format of the data you will receive and you can write your downstream client accordingly. Barring documentation you can parse a curl response and adjust accordingly, but what if the tables were turned and you needed to dynamically parse unknown JSON?

In Python, with a dynamic type system, this is relatively straight forward. Let’s parse and print the results such as in this example.

But what about the same thing in go? With go’s unusual type system the same code is not as straight forward.

Instead of unmarshalling into the custom pre-built type we wrote after reviewing the documentation we need to start by unmarshalling the JSON into a map of strings to interfaces with:

m := map[string]interface{}{}
err := json.Unmarshal([]byte(js), &m)
if err != nil {
    panic(err)
}

We are deserializing the json string js into the map m. Typically m would already be defined because we would know beforehand the structure of the JSON, but recall this is the opposite case and we have hit an endpoint where we do not already know the object.

From this point we can parse the map recursively to define all the types contained within the map using type assertions including nested types. In this example we print out the structure to the terminal, but a more useful case could be outputting to an AST to then generate a type file with methods that could operate on the provided JSON string.

The full working example of parsing and printing the json follows:

Go  REST 

See also