Sub topic 10
Dealing with Circular References
This chapter assumes you already know how a replacer function works and which values JSON.stringify cannot represent. You will see why cyclic data makes JSON.stringify fail, how to detect that failure, and two ways to serialize such data anyway.
Why Cycles Break JSON
A circular reference exists when an object can reach itself by following its own properties. DOM nodes do this, and so do parent/child trees where each child points back to its parent, and doubly linked lists. JSON text has no way to say "this is the same object as before". It can only nest values. When JSON.stringify walks a cycle, it would keep writing the same object inside itself forever. To prevent that, the engine tracks the objects it is currently serializing. When it finds one of them again, it throws a TypeError.
const parent = { name: "root", children: [] };
const child = { name: "leaf", parent };
parent.children.push(child);
try {
JSON.stringify(parent);
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message);
// V8: "Converting circular structure to JSON ..."
// Firefox: "cyclic object value"
}The error message differs between engines, so check instanceof TypeError rather than matching the text.
Option 1: Mark Every Repeated Reference
The simplest workaround is a replacer that remembers every object it has seen in a WeakSet and returns a marker string when an object shows up again.
function circularReplacer() {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) return "[Circular]";
seen.add(value);
}
return value;
};
}
const node = { name: "a" };
node.self = node;
console.log(JSON.stringify(node, circularReplacer()));
// {"name":"a","self":"[Circular]"}This approach has a common bug. The replacer marks any object it has already seen, including shared objects that are not part of a cycle:
const address = { city: "Oslo" };
const people = { home: address, work: address };
console.log(JSON.stringify(people, circularReplacer()));
// {"home":{"city":"Oslo"},"work":"[Circular]"}Here JSON.stringify(people) without the replacer works fine. With it, work silently loses its data.
Option 2: Track Only the Current Path
An object is part of a real cycle only if it appears among its own ancestors. Inside a replacer, this is the object that holds the current key. Keep a stack of ancestors, and pop entries until the top of the stack is this. That leaves only the path from the root to the current value. The replacer must be a regular function, because an arrow function does not get its own this.
function cycleSafeReplacer() {
const ancestors = [];
return function (key, value) {
if (typeof value !== "object" || value === null) return value;
while (ancestors.length > 0 && ancestors.at(-1) !== this) {
ancestors.pop();
}
if (ancestors.includes(value)) return "[Circular]";
ancestors.push(value);
return value;
};
}
const address = { city: "Oslo" };
const people = { home: address, work: address };
console.log(JSON.stringify(people, cycleSafeReplacer()));
// {"home":{"city":"Oslo"},"work":{"city":"Oslo"}}
const parent = { name: "root", children: [] };
parent.children.push({ name: "leaf", parent });
console.log(JSON.stringify(parent, cycleSafeReplacer()));
// {"name":"root","children":[{"name":"leaf","parent":"[Circular]"}]}Choosing an Approach
| Approach | Shared references | Cost | Use when |
|---|---|---|---|
| Let it throw, catch `TypeError` | Kept | None | Cycles indicate a bug |
| `WeakSet` replacer | Replaced by marker | Low | Debug logging of messy objects |
| Ancestor-stack replacer | Kept | Grows with nesting depth | Output must stay accurate |
| Remove the back-reference (for example with a `toJSON` that omits `parent`) | Kept | None | You own the data model |
For logging, Node's util.inspect already handles cycles and prints <ref *1> markers. That output is for reading, though, and it is not valid JSON.
Exercise
A list node is defined as const a = { v: 1 }; const b = { v: 2, prev: a }; a.next = b;. What do JSON.stringify(a, circularReplacer()) and JSON.stringify(a, cycleSafeReplacer()) print, and why are the results the same here?
Show answer
Both print {"v":1,"next":{"v":2,"prev":"[Circular]"}}. The only repeated reference is b.prev pointing back to a, which is an ancestor on the current path. That makes it a real cycle, so both replacers mark it. The two approaches only give different results for objects that are shared but not cyclic.
Exercise
Why does cycleSafeReplacer use function (key, value) instead of an arrow function?
Show answer
It needs this, which JSON.stringify sets to the object holding the current key, so it can drop ancestors that are no longer on the path. An arrow function inherits this from the scope around it, so the stack would never be trimmed correctly.