Trusted answers to developer questions

What is TypeError: Converting circular structure to JSON?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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.

RELATED TAGS

javascript

CONTRIBUTOR

Fahad Farid
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?