SyntaxStudy
Sign Up
JavaScript Circular References in JSON
JavaScript Advanced 5 min read

Circular References in JSON

Circular Reference Error

JSON.stringify throws a TypeError if the object contains circular references. Use structuredClone or a custom replacer to handle them.

Example
// 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;
  });
}
Pro Tip

Circular references usually indicate a design issue — consider redesigning the data structure to avoid them.