JSON serialization of interconnected object graphs
Thursday, August 21st, 2008In it’s basic form, JSON cannot serialize cyclic graphs of objects, or graphs where multiple paths can lead to the same object. In a project I’m working on, I wanted to move such a graph of highly-interconnected objects from JS to python. So I have invented a format built on top of JSON that can be used to serialize/deserialize such graphs.
Basically, the JSON comes across as a large list:
[ /* list[0] is the base object at the root of the eventual object graph. */ { /* string, number, true/false, and null properties are serialized directly */ "stringprop": "stringvalue", "numprop": 3.1415, /* but lists and objects are not serialized directly. Instead, they are represented by an index into the base list. "sharp" is a nod to JS sharp variables, from which this was originally inspired */ "complexprop": {"sharp": 1} }, /* list[1] is referenced from list[0].complexprop. It also references itself, see below */ [ "simplestring", 3, {"sharp": 1} ] ]
You can find JS for serializing these types of graphs here, and python for deserializing them here.
It turns out that I probably don’t actually need this code: I’ve found a simpler solution for my particular problem, but I wanted to share this solution in case other people might find it useful.