Skip to content
Search Journal
Search journal entries and projects across Journal.
Rust & Systemsdeep dive

Building JSON+: A Graph-Aware Serialization Format for JavaScript

How I designed a versioned JavaScript serialization format that preserves cycles, shared identity, built-ins and binary views while validating untrusted input.

JSON.stringify works well for tree-like data structures. Object properties with undefined values are omitted, BigInt and cyclic values cause errors, and shared references are serialized as separate objects. JSON+ is a versioned JSON format for a limited subset of JavaScript values. It supports cyclic references and shared identity. Functions, closures, symbols, DOM nodes, weak collections and arbitrary classes are not supported.

The key here is object identity. If first and second point to the same object, there will be one node with two edges coming into it. If an object points to itself, then there will be a cycle. This needs to be maintained in the wire format.

This is a very minimal format containing just format, version, root and nodes. Primitive values are encoded inline or explicitly (undefined, NaN, infinities, -0, and BigInt as canonical decimal). The encoder records the identity of a referenceable object the first time it encounters it, before walking its children. Any subsequent references will be encoded using { "$ref": n }.

The node table acts as a queue. A cursor is used to iterate over the nodes, and new objects are added to the end of the list. This keeps encoding iterative without needing another traversal structure.

Properties, array elements and Map entries have been flattened into alternating buffers. Encoding each pair as a tuple would create unnecessary garbage. Arrays contain indexes so holes remain holes rather than becoming explicit undefined values.

Decoding happens in separate phases:

parse → schema, refs, reachability, limits
      → allocate objects and buffers
      → wire edges
      → resolve root

By creating the nodes first, references and cycles are easy to handle. The decoder first validates the document and then builds the graph. If there are invalid tags, duplicate keys, invalid references, uneven pair buffers, misaligned typed array views, non-canonical Base64, unreachable nodes or oversized payloads, then a JSONPlusError will be thrown with a stable error code. Duplicate JSON keys are checked in the original text because JSON.parse would otherwise discard earlier values.

Normal objects, null-prototype objects, sparse arrays, Date, RegExp objects (including lastIndex as an edge in the graph), Map and Set (in insertion order), ArrayBuffer, typed arrays and DataView are supported. Views share the identity of their backing buffer. The buffer is created first so the view’s offset is real.

Value family Version 1 support Preserved contract
Objects and arrays Ordinary and null-prototype objects; sparse arrays Graph identity, cycles and array holes.
Built-ins Date, RegExp, Map, Set Map/Set insertion order; RegExp lastIndex.
Binary data ArrayBuffer, typed arrays, DataView Shared backing-buffer identity, offsets and view lengths.
Unsupported values Functions, symbols, DOM nodes, weak collections, arbitrary classes Rejected rather than silently flattened.

Getters are never called when encoding. Data properties are restored as writable and configurable. Normal and null prototypes are maintained. Property descriptors, extensibility and custom prototype chains are not serialized. Proxies are not supported because they can run traps when reflected upon. Resizable buffers and SharedArrayBuffer are also not supported.

The decoder validates untrusted documents to ensure they do not exceed the maximum number of nodes, edges, binary bytes, strings, collections or input/output length. If they do, RESOURCE_LIMIT_EXCEEDED will be thrown. This keeps the decoder from doing too much work. Actual memory usage will still depend on the values being reconstructed.

The encoder writes the supported graph format, and the decoder validates documents against that format before rebuilding the graph. Only version 1 is currently supported. If the schema changes, a new version will be created so existing documents retain their original meaning.

const shared = { id: 1 };
const input = { first: shared, second: shared };
input.self = input;

const output = decode(encode(input));
output.first === output.second; // true
output.self === output; // true

The two properties still point to the same object, and the self-reference still points back to the root.

Where JSON+ could go next

There’s still room to take JSON+ further. I’d like to test it against more real data, especially large graphs and binary-heavy values, and see where encoding and decoding spend their time. The current benchmarks cover plain object trees, cyclic graphs and shared binary buffers. More varied inputs would make it easier to see how the format behaves as graph shape and size change.

A streaming API is another possibility for large documents, although graph references and validation make that more involved than writing chunks of JSON. I’d also like to run the same round-trip and malformed-input tests across more browser runtimes. Any new value types or wire changes would need to fit the versioning rules rather than quietly changing what version 1 means.

For now, the useful part of JSON+ is that it keeps object identity in the data instead of trying to flatten a graph into a tree. That’s the part I’d keep building on.