Error Encyclopedia

JSON Circular Reference Error

Fix 'Converting circular structure to JSON' error when using JSON.stringify with objects that reference themselves.

What Does This Error Mean?

This error occurs when JSON.stringify() encounters an object that references itself (directly or indirectly), creating an infinite loop that cannot be serialized to JSON.

Common Causes

1

Parent-child relationships where the child references the parent

2

DOM node circular references (e.g., parentNode, childNodes)

3

Mongoose/Sequelize model instances with cyclic relationships

4

Event emitters or observable patterns with subscriber references

5

Cached data structures that include back-references

How to Fix It

Use a replacer function

Pass a replacer function to JSON.stringify to skip circular references.

const seen = new WeakSet()
const json = JSON.stringify(obj, (key, value) => {
  if (typeof value === "object" && value !== null) {
    if (seen.has(value)) return "[Circular]"
    seen.add(value)
  }
  return value
})

Use a library

Use util.inspect() in Node.js or a library like "flatted" or "json-stringify-safe" that handles circular references.

const stringify = require("json-stringify-safe")
const safe = stringify(circularObj)

Remove circular references

Before serializing, strip or nullify properties that create circular references.

function stripCircular(obj) {
  const { parent, children, ...clean } = obj
  return { ...clean, children: children.map(c => c.id) }
}

Before & After Examples

❌ Before
const tree = { name: "root", children: [] }
tree.parent = tree
JSON.stringify(tree)
✅ After
const tree = { name: "root", children: [] }
// Remove the circular reference before serializing
delete tree.parent
JSON.stringify(tree)

Related Tools

Use these tools to debug and fix this error:

Related Errors

Other common errors in this category:

Frequently Asked Questions

Can JSON represent circular references?

No. The JSON format does not support circular references. You must transform the data to remove cycles before serialization.

Is there a JSON format that supports circular references?

Not natively, but you can use serialization libraries like Flatted (based on JSON) that encode references, or use custom replacer/reviver pairs to serialize and restore circular structures.