Converting circular structure to JSON

I have recently encountered the below error while using the JSON.stringify for a class object.

Error:
"stack":["TypeError: Converting circular structure to JSON"," --> starting at object with constructor 'Cluster'"," | property '_source' -> object with constructor 'AutoconfSource'"," --- property '_cluster' closes the circle"," at JSON.stringify (<anonymous>)"

Let’s decode this in this article, so that it will be helpful for everyone.

So this error “Converting circular structure to JSON” typically happens in JavaScript (or Node.js) when we are trying to use JSON.stringify() on an object that contains a circular reference.

What is a Circular Structure?

A circular structure means an object refers to itself (directly or indirectly), which creates a loop.

For example:

const obj = {};
obj.self = obj;

JSON.stringify(obj); // Error: Converting circular structure to JSON

In this case, obj.self refers to obj itself, creating a loop. JSON.stringify() doesn’t know how to handle that, so it throws an error.

Solution: There are multiple solutions for this as below.

1. Remove or avoid circular references : Before stringifying, remove the circular part of the object:

const obj = {};
obj.self = obj;

// Remove circular reference
delete obj.self;

JSON.stringify(obj); // Works now

2. Use a library that can handle circular structures
You can use something like flatted:

npm install flatted
const { stringify, parse } = require('flatted');

const obj = {};
obj.self = obj;

const json = stringify(obj); // No error
console.log(json);            // Works fine

3. Custom replacer function in JSON.stringify

A custom replacer can help track and skip circular references:

function removeCircular() {
  const seen = new WeakSet();
  return (key, value) => {
    if (typeof value === "object" && value !== null) {
      if (seen.has(value)) return; // Skip circular
      seen.add(value);
    }
    return value;
  };
}

const obj = {};
obj.self = obj;

const json = JSON.stringify(obj, removeCircular());
console.log(json); // Works, circular reference skipped

I hope this helps everyone!, Feel free to comment for any suggestion or update to the article

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top