Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

What is TypeError: Converting circular structure to JSON?

Fahad Farid

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring