Fix - TypeError Converting circular structure to JSON in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

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 add a circular reference, in other words a value to the object that is the object itself, remove the piece of code from your application.

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 from 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 the object to the JSON.stringify() method.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee