Welcome to Coding Beez Learn at your own pace with structured courses designed for students and professionals. Find out more!

CodingBeez Logo

Converting circular structure to JSON

Converting Circular Structure to JSON in JavaScript
  • Prakash Pradhan By Prakash Pradhan
  • codingBeez_calendar Jan 31, 2026
  • codingBeez_bookmark NodeJS
  • codingBeez_comments 0 Comments

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

Prakash Pradhan

Prakash Pradhan

Sr. Software Engineer

Senior Software Engineer with 10+ years of experience in designing and scaling distributed systems and full-stack applications. Experts in optimizing system performance, and delivering high-impact technical solutions across the entire software development lifecycle.

Comments

No comments yet.

You need to login to comment

Recent Posts