TypeError: Converting circular structure to JSON in JS

avatar
Borislav Hadzhiev

Last updated: Mar 2, 2024
3 min

banner

# TypeError: Converting circular structure to JSON in JS

The "Converting circular structure to JSON" error occurs when we pass an object that contains circular references to the JSON.stringify() method.

To solve the error, make sure to remove any circular references before converting the object to JSON.

typerror converting circular structure to json

Here are two examples of how the error occurs.

index.js
const obj = {}; obj.name = obj; // ⛔️ TypeError: Converting circular structure to JSON console.log(JSON.stringify(obj)); // ------------------------------------------------- const arr = [{}]; arr[0].arr = arr; // ⛔️ TypeError: Converting circular structure to JSON JSON.stringify(arr);

We set a property on the object that points to the object itself - that's a circular reference.

The JSON.stringify method doesn't support circular references, so we have to remove them before converting the object to JSON.

If you spot where you have a circular reference, in other words, a value in the object that is the object itself, remove it before converting to JSON.

# Things to note

Here are some things to note:

  • Make sure to remove any unnecessary console.log() calls related to the object from your code as they also might cause the error.

  • A common cause of the error is forgetting to await a promise.

  • Some APIs call JSON.stringify() automatically, so you don't have to, e.g. res.json(obj). We don't have to call JSON.stringify() with obj because the res.json() method automatically does that for us.

Try to remove the call to JSON.stringify() and see if your code works (some API might be calling the method for you).

Alternatively, you can use a function to remove all circular references from an object.

# Use a method to remove all circular references from an object

Here's an example of how to remove circular references from an object.

index.js
const getCircularReplacer = () => { const seen = new WeakSet(); return (key, value) => { if (typeof value === 'object' && value !== null) { if (seen.has(value)) { return; } seen.add(value); } return value; }; }; const obj = { address: {country: 'Chile'}, numbers: [1, 2, 3], age: 30, }; obj.name = obj; // ✅ Works const result = JSON.stringify(obj, getCircularReplacer()); console.log(result); // 👉️ {"address":{"country":"Chile"},"numbers":[1,2,3],"age":30}

use method to remove all circular references from an object

The code for this article is available on GitHub

We passed the result of calling the getCircularReplacer function as the second parameter to the JSON.stringify() method.

The second parameter enables us to control which values get stringified and which don't.

The function removes any circular references from the object, so we don't get an error when passing it to the JSON.stringify() method.

Alternatively, you can use the flatted package - a light and fast circular JSON parser.

# Use the flatted package to resolve circular references

First, open your terminal in your project's root directory to install the package.

shell
# 👇️ with NPM npm install flatted # 👇️ with YARN yarn add flatted

Now you can use the stringify() method from the flatted package.

index.js
import {parse, stringify, toJSON, fromJSON} from 'flatted'; const arr = [{}]; arr[0].arr = arr; arr.push(arr); const result = stringify(arr); // [["1","0"],{"a":"0"}] console.log(result); // 👉️ [["1","0"],{"arr":"0"}]

use flatted package to resolve circular dependencies

The code for this article is available on GitHub

The code sample uses the ES6 import/export syntax, if you use require(), update your import statement.

index.js
// 👇️ using CJS (require()) const {parse, stringify, toJSON, fromJSON} = require('flatted'); const arr = [{}]; arr[0].arr = arr; arr.push(arr); const result = stringify(arr); // [["1","0"],{"a":"0"}] console.log(result); // 👉️ [["1","0"],{"arr":"0"}]

You can read more about how to use the flatted package in the package's NPM page.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.