JSON.stringify Throws On Circular References

stringify refuses cyclic object graphs with a TypeError, so log paths must break the cycle first or steer around the cyclic key with a replacer.

JavascriptResilience

Code

javascriptsnippet
13 lines
const node = { id: 1, next: null };
node.next = node; // linked-list style circular reference

// JSON.stringify throws a TypeError as soon as it hits a circular reference
try {
  JSON.stringify(node);
} catch (err) {
  console.log('error:', err instanceof TypeError);
}

// the logging path uses a replacer to skip the cycle-forming key instead of letting the whole serialization crash
const safe = JSON.stringify(node, (key, value) => (key === 'next' ? '[linked]' : value));
console.log('safe:', safe);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

error: true
safe: {"id":1,"next":"[linked]"}

How it works

All the work happens on the top-level bindings: node, safe.

One object literal carries id, next — every value is written inline.

What to watch for

  • Ready as-is on a bare install of the language.

Applying it

Look for the error:, safe: prefixes during the file’s run; they match each line of output to the step that emitted it.

Statements that decide the outcome

const safe = JSON.stringify(node, (key, value) => (key === 'next' ? '[linked]' : value));
JSON.stringify(node);

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Its state lives in module-level bindings: `node`, `safe`.