What is TypeError: Converting circular structure to JSON?

TypeError: Converting circular structure to JSON occurs when you try to reference your variable name within the JSON object.

var mycar ={}
mycar.a = mycar
JSON.stringify(mycar)

The code above will give an error since JSON.stringify is unable to convert such structures. This also happens to DOM nodes with circular references.

Solutions

1. Removing dependencie

Try to remove any circular dependencies that have been created in the code.

2. Use the flatted package

You can use the flatted package to solve the issue. Take a look at the example code given below:

const {parse, stringify} = require('flatted/cjs');
const mycar = {};
mycar.a = mycar;
stringify(mycar);
console.log(mycar)

3. Remove the console.logs

At times, printing a value that has already been referenced might create circular dependency. However, if you remove such print statements, and the code should work.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved