Sub topic 10
Dealing with Circular References
This chapter assumes you already know how JSON.stringify walks an object, how a replacer function receives key and value, and how toJSON works. Here you will learn why some objects cannot be turned into JSON at all, how to detect that case, and the main ways to work around it. Each workaround loses something, and the chapter points out what.
What a Circular Reference Is
A circular reference, or cycle, exists when an object can reach itself by following its own properties. The simplest cycle is an object that points to itself. Real cycles are usually longer. A child points to its parent, two users list each other as friends, or a DOM node references its document, which references the node again.
JavaScript objects handle cycles without trouble, because a property holds a reference, not a copy. JSON text is a tree with no references. To write an object, JSON.stringify must write out the full contents of every nested value. If one of those values is an ancestor of itself, the writing never ends. The specification therefore requires stringify to keep a stack of the objects it is currently serializing. If it meets an object that is already on that stack, it throws a TypeError.
Seeing the Error
const node = { name: "a" };
node.self = node;
try {
JSON.stringify(node);
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message);
}The message depends on the engine:
| Engine | Typical message |
|---|---|
| V8 (Chrome, Node.js, Deno) | `Converting circular structure to JSON --> starting at object with constructor 'Object' --- property 'self' closes the circle` |
| SpiderMonkey (Firefox) | `cyclic object value` |
| JavaScriptCore (Safari, Bun) | `JSON.stringify cannot serialize cyclic structures.` |
Do not match on the message text in your code. It differs across engines and may change between versions. If you need to treat this failure as a separate case, check err instanceof TypeError. Keep in mind that a BigInt value or a toJSON method that throws can also cause a TypeError during stringify.
Option 1: Mark Repeated Objects with a WeakSet
The most common quick fix is a replacer that remembers every object it has already seen and puts a marker string in place of any object it meets a second time. A WeakSet works well for this. It holds objects only, and it does not keep them alive once the call finishes.
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]"}Note that circularReplacer() is a factory. Call it once for each stringify call so that every serialization starts with an empty set. If you reuse one replacer across calls, objects from the first call will be marked as circular in the second.
The Gotcha: Shared References Are Not Cycles
The WeakSet approach cannot tell a real cycle from an object that simply appears twice:
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 address = { city: "Lyon" };
const order = { billing: address, shipping: address };
console.log(JSON.stringify(order));
// {"billing":{"city":"Lyon"},"shipping":{"city":"Lyon"}}
console.log(JSON.stringify(order, circularReplacer()));
// {"billing":{"city":"Lyon"},"shipping":"[Circular]"}Plain JSON.stringify handles this object fine, because there is no cycle. It writes the shared object twice. The WeakSet replacer damages the data by replacing the second copy with a marker. For log output this may be acceptable. For data that another system will read, it is a bug.
Option 2: Track Only the Current Ancestors
To mark only true cycles, check whether the value is an ancestor of the current position, not whether it was seen anywhere. Inside a replacer written as a regular function, this is the object that holds the current key. You can use it to keep a stack of ancestors that matches the path stringify is currently on.
function cycleSafeReplacer() {
const ancestors = [];
return function (key, value) {
if (typeof value !== "object" || value === null) return value;
// Pop until the top of the stack is the object holding this key.
while (ancestors.length > 0 && ancestors.at(-1) !== this) {
ancestors.pop();
}
if (ancestors.includes(value)) return "[Circular]";
ancestors.push(value);
return value;
};
}
const address = { city: "Lyon" };
const order = { billing: address, shipping: address };
console.log(JSON.stringify(order, cycleSafeReplacer()));
// {"billing":{"city":"Lyon"},"shipping":{"city":"Lyon"}}
const node = { name: "a" };
node.self = node;
console.log(JSON.stringify(node, cycleSafeReplacer()));
// {"name":"a","self":"[Circular]"}Here is how the stack works. For the root call, this is a wrapper object {"": root} and the stack is empty, so the root gets pushed. When stringify moves to a sibling property, the object holding that sibling is lower on the stack, so the loop pops the branch that is finished. Only the objects on the current path remain.
Costs to keep in mind:
ancestors.includesis a linear scan, so very deep nesting gets slower. For normal data the depth is small and this does not matter.- The output still contains a marker string. A reader of the JSON cannot rebuild the original link from
"[Circular]". - The replacer sees each value after
toJSONhas run, so it checks the converted value, not the original object.
Option 3: Change the Shape of the Data
The markers above are fine for logging and debugging. When the JSON needs to be read back into a working structure, the better fix is to leave out the links that cause cycles and rebuild them after parsing. JSON can express data and identifiers. It cannot express object identity, so you serialize the data and recreate the identity yourself.
Drop Back-References and Restore Them
Parent pointers in a tree are redundant, because the nesting already says who the parent is.
const root = { name: "root", children: [] };
const child = { name: "child", children: [], parent: root };
root.children.push(child);
const text = JSON.stringify(root, (key, value) =>
key === "parent" ? undefined : value
);
console.log(text);
// {"name":"root","children":[{"name":"child","children":[]}]}
function restoreParents(node, parent = null) {
if (parent) node.parent = parent;
for (const c of node.children) restoreParents(c, node);
return node;
}
const restored = restoreParents(JSON.parse(text));
console.log(restored.children[0].parent === restored); // trueThe replacer drops every key named parent at every depth. If some unrelated nested object also has a parent field that you want to keep, this replacer will remove it too. In that case, check this or the value's type, or use toJSON, which is shown next.
Put the Rule on the Class with toJSON
If you own the class, define what it serializes as in one place:
class TreeNode {
constructor(name, parent = null) {
this.name = name;
this.parent = parent;
this.children = [];
if (parent) parent.children.push(this);
}
toJSON() {
return { name: this.name, children: this.children };
}
}
const root = new TreeNode("root");
new TreeNode("left", root);
new TreeNode("right", root);
console.log(JSON.stringify(root));
// {"name":"root","children":[{"name":"left","children":[]},{"name":"right","children":[]}]}stringify calls toJSON on each child as it reaches it, so the whole tree comes out clean without a replacer.
Replace Object Links with IDs
General graphs, where any object can point to any other, have no natural nesting. Give each object an ID and store the ID in place of the reference:
const alice = { id: 1, name: "Alice" };
const bob = { id: 2, name: "Bob" };
alice.friend = bob;
bob.friend = alice;
const text = JSON.stringify([alice, bob], (key, value) =>
key === "friend" ? value.id : value
);
console.log(text);
// [{"id":1,"name":"Alice","friend":2},{"id":2,"name":"Bob","friend":1}]
const people = JSON.parse(text);
const byId = new Map(people.map((p) => [p.id, p]));
for (const p of people) p.friend = byId.get(p.friend);
console.log(people[0].friend.friend === people[0]); // trueThis is the same approach databases and most APIs use. It also keeps shared objects shared: two orders pointing at address 5 will point at the same rebuilt object after parsing.
Choosing an Approach
| Approach | Handles shared refs correctly | Can be read back into the original structure | Best for |
|---|---|---|---|
| Plain `JSON.stringify` | Yes, by duplicating them | Only acyclic data | Data with no cycles |
| WeakSet replacer | No, marks them | No | Quick logging |
| Ancestor-stack replacer | Yes | No, markers are lossy | Logging and debugging dumps |
| Drop back-references and rebuild | Yes | Yes | Trees with parent pointers |
| `toJSON` on the class | Yes | Yes, with a rebuild step | Classes you own |
| ID references | Yes, and identity is kept | Yes | Graphs, APIs, storage |
If you only need an in-memory copy and do not need text, structuredClone copies cycles and shared references directly. A later chapter compares it with JSON round-tripping.
Exercises
Exercise
You serialize const tag = { label: "x" }; const post = { tags: [tag, tag] }; with the WeakSet-based circularReplacer. What is the output, and what does plain JSON.stringify(post) produce?
Show answer
The WeakSet replacer produces {"tags":[{"label":"x"},"[Circular]"]} because it marks the second occurrence of tag even though there is no cycle. Plain JSON.stringify(post) succeeds and produces {"tags":[{"label":"x"},{"label":"x"}]}.
Exercise
A teammate rewrites cycleSafeReplacer using an arrow function: return (key, value) => { ... ancestors.at(-1) !== this ... }. Why does it break?
Show answer
Arrow functions do not get their own this. Inside the arrow, this comes from the enclosing scope, which is the factory's this (undefined in strict mode) and not the holder object that stringify passes. The while loop then pops the whole stack every time, so real cycles are never found, and stringify throws the TypeError again on a cyclic input.
Exercise
Employees have a manager property pointing to another employee object, and managers can be employees of each other's departments, so cycles are possible. You need to save the list to localStorage and restore it with the links working. Which approach fits, and how would you restore it?
Show answer
Use ID references. Serialize with a replacer that returns value.id when key === "manager" (or null if there is no manager). After JSON.parse, build a Map from id to employee and set each employee's manager to byId.get(employee.manager). Marker-based replacers would lose the links, and removing the field without IDs would lose the information.