Fix - TypeError Converting circular structure to JSON in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Fix - TypeError Converting circular structure to JSON #

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 some 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 does not 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.

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

Here's an example of how to remove the 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}

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.

Use the search field on my Home Page to filter through my more than 3,000 articles.