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.
Code
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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.