Troubleshooting Knowledge Base

Handling Circular References in JSON.stringify()

Fix "TypeError: Converting circular structure to JSON" from JSON.stringify(). Detection techniques, replacer functions, and the flatted library explained.

"TypeError: Converting circular structure to JSON" occurs when you call JSON.stringify() on an object that contains a reference back to itself or to a parent object. Use a custom replacer function or a library like flatted to handle circular references.

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

  1. Custom replacer function: Track seen objects with a WeakSet and return undefined for circular refs.
  2. json-stringify-safe: Drop-in replacement for JSON.stringify that replaces circular references with "[Circular]".
  3. flatted: Library that serializes circular structures using a special encoding.
  4. Restructure data: Remove the circular reference from the data model before serializing.
json
// 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

Try the free JSON Formatter

Runs entirely in your browser — no upload, no signup, and your data never leaves your device.

Open JSON Formatter

Frequently Asked Questions

What causes "Converting circular structure to JSON"?

This error occurs when JSON.stringify() encounters an object that references itself (directly or via a chain of references), creating an infinite loop.

How do I detect a circular reference in JavaScript?

Use a WeakSet to track all seen objects during traversal. If you encounter an object already in the set, it is circular.

Can I use JSON.stringify on circular data?

Not directly. Use a custom replacer function or a library like flatted or json-stringify-safe to handle circular references.

Related JSON Topics & Reference Articles