deriving json types in Go

At smugmug, I am currently writing code to support a proxy to a remote service that formats messages in json. A good strategy in Go is to create a type that matches the shape of the expected data. The example below is a trivial example of matching json of a known shape to a native type:

gist

Using a technique like this, we can use robust native typing to help us detect when json doesn't match its expected shape.

But what do we do when json has a shape that varies? Typically in Go we utilize

interface {}
to match structures of an unknown shape, and let Go automatically create an opaque data structure. But what if we want to derive more useful native types? Consider some variations in json that show up in messages seen from our remote service:

gist

Go has powerful value inspection mechanisms for helping us determine how to get these bits into native types, and we can also use some intuition - we know that when we see a key of either SS or NS, we have lists of interface {} values. Using what we know, four functions emerge to help derive native types:

gist

Now we have native types that preserve the safety of the rest of our system.

last update 2012-03-24