Serialize object graphs with Maps, Sets, cycles, shared refs
A whiteboard app keeps its document as an object graph: shapes live in a Map keyed by shape object, a Set holds the selected shapes, and every shape points back to its parent layer. JSON.stringify cannot save this. It turns a Map into {}, throws on cycles, and writes a shared object twice, so after loading, editing one copy no longer updates the other.
Build graphJSON, an object with two methods:
graphJSON.stringify(value) // => string (valid JSON)
graphJSON.parse(text) // => a rebuilt copy of value
parse only needs to accept strings produced by your own stringify. The encoding format is up to you.
null, booleans, strings, and finite numbers.Object.prototype), keeping element and key order.Map and Set, keeping insertion order. Map keys and Set members can be any supported value, including objects.These can be nested in any combination.
graphJSON.parse(graphJSON.stringify(value)) has the same shape, types, and order as value, built from new objects.copy.a === copy.b). That includes Map keys and Set members: a Map keyed by an object that also appears elsewhere is keyed by that same rebuilt object.{ $ref: 0 }, [0], or the string '#1'). It must still come back as itself.stringify throws a TypeError if it finds, at any depth: undefined, a function, a symbol, a BigInt, NaN, Infinity or -Infinity, or any other kind of object (such as a Date, a RegExp, or a class instance).stringify must not modify its input. Inputs can contain thousands of objects.const layer = { name: 'Sketch', shapes: [] };
const circle = { kind: 'circle', r: 12, layer };
layer.shapes.push(circle);
const doc = {
layers: [layer],
byId: new Map([['c1', circle]]),
selection: new Set([circle]),
};
const text = graphJSON.stringify(doc);
JSON.parse(text); // does not throw
const copy = graphJSON.parse(text);
const c = copy.byId.get('c1');
c === copy.layers[0].shapes[0]; // => true (shared)
copy.selection.has(c); // => true (same object)
c.layer === copy.layers[0]; // => true (cycle restored)
c === circle; // => false (new objects)
const self = new Map();
self.set('me', self);
const back = graphJSON.parse(graphJSON.stringify(self));
back.get('me') === back; // => true
graphJSON.stringify({ when: new Date() }); // throws TypeError
graphJSON.stringify([1, undefined]); // throws TypeError