Circular Reference Error
JSON.stringify throws a TypeError if the object contains circular references. Use structuredClone or a custom replacer to handle them.
JSON.stringify throws a TypeError if the object contains circular references. Use structuredClone or a custom replacer to handle them.
// This causes TypeError: circular structure
const a = {};
const b = { ref: a };
a.ref = b;
JSON.stringify(a); // TypeError!
// Solution: custom replacer that tracks seen objects
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;
});
}
Circular references usually indicate a design issue — consider redesigning the data structure to avoid them.
More in JavaScript