Circular References in JavaScript Objects
A circular reference occurs when an object directly or indirectly references itself. JSON.stringify() cannot serialize circular structures because JSON is a tree format with no concept of object identity or reference reuse.
Solutions
- Custom replacer function: Track seen objects with a WeakSet and return
undefinedfor circular refs. - json-stringify-safe: Drop-in replacement for JSON.stringify that replaces circular references with
"[Circular]". - flatted: Library that serializes circular structures using a special encoding.
- Restructure data: Remove the circular reference from the data model before serializing.
// Creating a circular reference
const obj = { name: 'Alice' };
obj.self = obj; // Circular reference!
JSON.stringify(obj); // ❌ TypeError: Converting circular structure to JSON
// Solution 1: Custom replacer with WeakSet
function safeStringify(obj) {
const seen = new WeakSet();
return JSON.stringify(obj, (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) return '[Circular]';
seen.add(value);
}
return value;
}, 2);
}
// Solution 2: flatted library
import { stringify, parse } from 'flatted';
const json = stringify(circularObj); // Handles circular refs
const restored = parse(json); // Restores structure