This error message «TypeError: Converting circular structure to JSON» typically occurs when you try to stringify an object that contains circular references using JSON.stringify().
A circular reference occurs when an object references itself in some way. For example, consider the following code:
const obj = { foo: {} };
obj.foo.obj = obj;
In this example, obj contains a circular reference because the foo property of obj contains a reference to obj itself.
When you try to stringify an object like this using JSON.stringify(), it will fail with the error message «TypeError: Converting circular structure to JSON».
To solve this issue, you can use a third-party library like flatted or circular-json, which are specifically designed to handle circular references in JavaScript objects. Here’s an example using flatted:
const flatted = require('flatted');
const obj = { foo: {} };
obj.foo.obj = obj;
const str = flatted.stringify(obj);
console.log(str);
In this example, we use flatted.stringify() instead of JSON.stringify(), and it successfully converts the object to a string without throwing an error.
Alternatively, you can modify your object to remove the circular reference before trying to stringify it. For example:
const obj = { foo: {} };
obj.foo.bar = 'baz';
// add circular reference
obj.foo.obj = obj;
// remove circular reference
obj.foo.obj = undefined;
const str = JSON.stringify(obj);
console.log(str);
In this example, we add the circular reference and then remove it before trying to stringify the object. This approach works well if you don’t need to preserve the circular reference in the stringified object.
I think I speak for everyone who is a newbie at JavaScript or is currently studying JavaScript when I say there is nothing more frustrating than attempting to find the error in your code and still not being able to do it after trying for hours. Even after spending hours looking at the same lines of code, you can still miss the error. But as any seasoned programmer will tell you, the secret to identifying the issue is to sit back and look at the big picture and the overall flow of the program. Of course, there are situations when, despite your best efforts, you cannot understand the error in your code. If you are getting the error “TypeError: Converting circular structure to JSON in JS” you’ve come to the right place. In this blog, we will discuss what exactly a Type Error is, how it can occur in Java Script and how to get rid of it for good.
What exactly is TypeError?
Let us first learn how JavaScript errors work in order to understand TypeError. In addition to logical errors, JavaScript also has two more sorts of errors: runtime errors and syntax errors (we commonly call them exceptions).
Syntax errors occur when the compiler detects an incorrect statement. However, TypeError in this instance is a runtime issue. When software crashes even though the syntax is correct, it is most probably a runtime error. Depending on the kind of error the program encounters, there are all kinds of runtime errors, including TypeError.
When an exception occurs, along with the error message, the kind of exception your program encountered (in this case, TypeError) is shown in the output. “Converting circular structure to JSON” is the error message that appears in our situation, telling us that there is a problem with the object we are trying to convert to JSON. When we attempt to access or pass a method or property of an unexpected type, we encounter a TypeError.
When does this error occur?
This error occurs when you try to convert a JavaScript object to JSON, but the object contains a circular reference. A circular reference occurs when an object refers to itself, directly or indirectly. For example, imagine you have a JavaScript object with a property that references the object itself:
Code language: JavaScript (javascript)
let obj = { name: "Codedamn", parent: null } obj.parent = obj;
In this case, the obj object contains a circular reference because the parent property references the obj object. When you try to convert this object to JSON, you’ll get the “TypeError: Converting circular structure to JSON” error because JSON.stringify()
(the method used to convert JavaScript objects to JSON) doesn’t support circular references.
The solution
Thankfully, the solution to this TypeError problem is pretty straightforward. To fix this error, you need to make sure that your objects don’t contain circular references. One way to do this is to use a library like JSONC that supports converting circular structures to JSON. Alternatively, you can manually detect and remove circular references from your objects before calling JSON.stringify()
.
Here is a simple code snippet that will let you ignore properties with circular references in an object:
Code language: JavaScript (javascript)
function stringify(obj) { let cache = []; let str = JSON.stringify(obj, function(key, value) { if (typeof value === "object" && value !== null) { if (cache.indexOf(value) !== -1) { // Circular reference found, discard key return; } // Store value in our collection cache.push(value); } return value; }); cache = null; // reset the cache return str; }
In this function, we use the JSON.stringify()
method’s second argument (the replacer function) to detect and remove circular references from the object before converting it to JSON. We do this by keeping track of all the objects we have seen in a cache array and checking if the current value is already in the cache. If it is, we return undefined
to remove the value from the final JSON string.
With this function, you can safely convert objects with circular references to JSON without getting the “TypeError: Converting circular structure to JSON” error. Just remember to use this function instead of JSON.stringify()
whenever you need to convert an object to JSON.
Conclusion
The first thing you should do when you encounter an issue is to Google it. It’s likely that another programmer has already dealt with this problem and found a solution! You may make it easier to debug your code by organizing it and adding comments. It is frequently helpful to print out the values of variables during debugging to identify the issue. In order to discover and correct mistakes, you can also use a debugging tool like a linter or a debugger. In this article, we understood the meaning of the error message “TypeError: Converting circular structure to JSON”. We looked at when this error message might occur and the possible actions you can take to get rid of it. I hope this article has cleared all your doubts regarding circular structures, and how it can be a problem with the JSON.stringify()
method.
If you have any questions regarding this article or want to talk about anything technology, you can find me on Twitter. Thank you for reading!
Become The Best JavaScript Developer 🚀
Codedamn is the best place to become a proficient developer. Get access to hunderes of practice JavaScript courses, labs, and become employable full-stack JavaScript web developer.
Free money-back guarantee
Unlimited access to all platform courses
100’s of practice projects included
ChatGPT Based Instant AI Help (Jarvis)
Structured Full-Stack Web Developer Roadmap To Get A Job
Exclusive community for events, workshops
Start Learning
In this article, I will help you fix the TypeError: Converting circular structure to JSON in JavaScript. What is the cause of it, and how to solve it? Let’s go into details now.
The error occurs when an object has a property that points to itself. JSON.stringify()
will return that error.
Code sample:
let bookObj = { title: "math", pages: 350, author: [{ name: "John" }, { name: "Jade" }] }; bookObj.language = bookObj; console.log(JSON.stringify(bookObj));
Output:
The code above, JSON.stringify()
give the error because JSON.stringify() is not supported if the object has circular references.
How to fix this error
Pass in an array of properties for JSON.stringify()
Syntax
JSON.stringify(value, replacer, space)
Parameters
- value: is the input value to be converted to a string (required).
- replacer: array of properties used to convert to string or a function(key, value)- called for each object’s property (optional).
- space: the number of space characters used to format JSON in Javascript (optional).
Code sample:
let bookObj = { title: "math", pages: 350, author: [{ name: "John" }, { name: "Jade" }] }; bookObj.language = bookObj; console.log(JSON.stringify(bookObj, ["title", "pages", "author"]));
Output
{"title":"math","pages":350,"author":[{},{}]}
Now, JSON.stringify()
does not have the above circular reference error. But the elements inside the author array are empty objects {}. That’s because the name attribute is not listed.
You can customize the allowed property list to accept all properties except the property with the circular reference as follows:
let bookObj = { title: "math", pages: 350, author: [{ name: "John" }, { name: "Jade" }] }; bookObj.language = bookObj; console.log(JSON.stringify(bookObj, ["title", "pages", "author", "name"]));
Output
{"title":"math","pages":350,"author":[{"name":"John"},{"name":"Jade"}]}
All properties (except language) have been included in the JSON. However, the usage is still quite lengthy. You can use the replacer function instead of arrays to solve this problem.
Use replacer() function
The replacer()
function is called for each (key, value) pair in the object and returns the replaced values or returns undefined if you want to omit that property.
Code sample:
let bookObj = { title: "math", pages: 350, author: [{ name: "John" }, { name: "Jade" }] }; bookObj.language = bookObj; function replacer(key, value) { return key == "language" ? undefined : value; } console.log(JSON.stringify(bookObj, replacer));
Output
{"title":"math","pages":350,"author":[{"name":"John"},{"name":"Jade"}]}
Summary
Above, I showed you how to fix the TypeError: Converting circular structure to JSON in JS. I hope they are helpful to you. To better understand the lesson’s content, practice rewriting today’s examples. And let’s learn more about JSON in the next lessons here. Have a great day!
Maybe you are interested:
- TypeError: filter is not a function in JavaScript
- TypeError: indexOf is not a function in JavaScript
- TypeError: querySelectorAll is not a function in JS
- TypeError: Cannot read property ‘top’ of Undefined in JS
Hi, my name is Joni Smith. My job is a programmer. I love learning programming languages, especially C++, C#, php, javascript, html, css. I want to share them with you. I hope my articles will bring a lot of useful knowledge to you.
Name of the university: HVNH BA
Major: htttql MIS
Programming Languages: C++, C#, php, javascript, html, css
Trusted answers to developer questions
Checkout some of our related courses
Learning Python through PowerShell Concepts
Harnessing the Power of the Command-Line Interface
Web Development: Unraveling HTML, CSS, and JavaScript
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.
Copyright ©2023 Educative, Inc. All rights reserved
Learn in-demand tech skills in half the time
Copyright ©2023 Educative, Inc. All rights reserved.
Did you find this helpful?
TypeError Converting circular structure to JSON error occurs in JavaScript when an object with circular references is passed to “JSON.stringify()”. If you don’t know the cause of the error, this article is for you because we’ll teach you how it occurred and how you can fix it.
To do this, we’ll use different code examples that will give you a good understanding of the error in Vanilla JavaScript and other JavaScript libraries. That’s it for the overview of what you’re about to learn; now get your code that’s showing the error, and let’s fix it.
Contents
- Why a Circular Structure to Json Conversion Error Occurs?
- – You Want to Stringify an Object With Circular References
- How To Fix the Circular Structure to Json Conversion Error?
- – Extract Only the Necessary Data From the Response Object
- – Use “Flatted” to Serialize and Deserialize Your Data
- – Stringify Only the Form Values When Working With Angular
- – Allow the “Request” Module to “Stringify” Your Object
- – Use a Serializer Function That Can Handle Circular Objects
- Conclusion
Why a Circular Structure to Json Conversion Error Occurs?
A circular structure to JSON conversion error occurred in your code because you want to “stringify” a JavaScript object with circular references. The error arises due to the limitations of “JSON.stringify()” when it tries to serialize an object with circular references.
– You Want to Stringify an Object With Circular References
Any attempts to “stringify” an object with circular references will lead to a “TypeError” followed by the detailed error message which is the focus of this article. The term “circular references” means an object that refers to itself, directly or indirectly, through another JavaScript object.
This creates an infinite loop and when “JSON.stringify()” detects this, it throws the error to prevent infinite recursion. For example, the following JavaScript code will lead to the “TypeError: converting circular structure to JSON” because the object contains a property “meme” that references the object.
“first”: “Federico”,
“last”: “Fernandez”
}
// Create a circular reference
obj.meme = obj;
// The following will throw a conversion
// error.
JSON.stringify(obj);
What’s more, you can see this error if you’re working with Vanilla JavaScript or JavaScript libraries and frameworks. That’s because they’re using “JSON.stringify()” to serialize JSON data, and the following table highlights possible causes of this error. In the next section, we’ll use the table as a template and show you code samples that can lead to the error and how you can fix them.
JavaScript Library / Framework / Environment | Possible Cause of the Error |
Axios, NestJS, and “Express.js” | Your API response object contains circular references. |
Angular | You’re trying to “stringify” an entire form object. |
NodeJS | Your code is trying to “stringify” the “request” object. |
Jest | You’re using the “expect()” method to compare objects that contain circular references. |
Mongoose | You’re trying to convert an object with circular references. |
ReactJS | You have circular references in your component’s state or props. |
How To Fix the Circular Structure to Json Conversion Error?
To fix the circular structure to JSON conversion errors, you should use only the necessary data from a response object. The “flatted” package also works and in Angular, you can “stringify” only the form values. In NodeJS, you should allow the “request” module to automatically “stringify” your object.
Finally, in your Jest testing code, you can use a custom serializer function that can handle circular objects.
The extraction of only the necessary data from the response object will solve the “TypeError: Converting circular structure to JSON NestJS” error. That’s because NestJS uses Axios under the hood, and the Axios response object contains circular references. For example, the following code returns the entire response object leading to the error.
import { HttpService } from ‘@nestjs/axios’;
import { AxiosResponse } from ‘axios’;
@Controller()
export class AppController {
constructor(private httpService: HttpService) {}
@Get()
async getData(): Promise<AxiosResponse> {
const url = “https://example.com/api/data”;
const response = await this.httpService.get(url).toPromise();
return response; // this returns the entire response object, including circular references
}
}
The following is a fix, and we’re using the “map()” operator to extract only the data property from the response object. Since NestJS uses Axios, you can use the same approach to solve the “TypeError: Converting circular structure to JSON Axios” error.
import { HttpService } from ‘@nestjs/axios’;
@Controller()
export class AppController {
constructor(private httpService: HttpService) {}
@Get()
async getData(): Promise<any> {
const url = ‘https://example.com/api/data’;
// The following line will fix the error because it
// returns only the data from the response.
const response = await this.httpService.get(url).pipe(map((resp) => resp.data)).toPromise();
return response;
}
}
– Use “Flatted” to Serialize and Deserialize Your Data
The “flatted” package can solve the “TypeError: Converting circular structure to JSON Mongoose” error because it can serialize your data. In Mongoose, this error mostly happens if you call the “toJSON” method on an object with circular references. For example, in the following, the “User” model has a circular reference to the “User” documents. This will cause the error later in the code when we call “toJSON” on the “alice” object.
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: String,
friends: [{ type: Schema.Types.ObjectId, ref: ‘User’ }],
});
const User = mongoose.model(‘User’, UserSchema);
(async () => {
await mongoose.connect(‘mongodb://localhost/test’);
const alice = new User({ username: ‘Alice’ });
const bob = new User({ username: ‘Bob’ });
const charlie = new User({ username: ‘Charlie’ });
alice.friends.push(bob);
bob.friends.push(charlie);
charlie.friends.push(alice);
await Promise.all([alice.save(), bob.save(), charlie.save()]);
try {
const aliceJson = alice.toJSON();
console.log(aliceJson);
} catch (error) {
console.error(error);
} finally {
await mongoose.connection.close();
}
})();
In the code above, the “flatted” package, via its “stringify()” method, can help fix the circular references error because it can handle such references from the object returned by “toJSON”. What’s more, it can solve the “TypeError: Converting circular structure to JSON React” using “flatted.parse(flatted.stringify(object_with_circular_references)).
// Install “flatted” and import it.
const flatted = require(‘flatted’);
/* The remaining code remains the same. */
try {
const aliceJson = flatted.stringify(alice.toJSON()); // Here is the fix for the previous code.
console.log(aliceJson);
} catch (error) {
console.error(error);
} finally {
await mongoose.connection.close();
}
})();
– Stringify Only the Form Values When Working With Angular
If you’re seeing the “TypeError: Converting circular structure to JSON Angular” error, it’s possible that you’re applying “JSON.stringify()” on your form object. For example, the following code will result in the error because we’re calling “JSON.stringify()” on “this.myForm”.
import { HttpClient } from ‘@angular/common/http’;
import { FormGroup, FormControl } from ‘@angular/forms’;
@Component({
selector: ‘app-root’,
template: `
<form [formGroup]=”myForm”>
<input type=”text” formControlName=”username” placeholder=”Username”>
<input type=”text” formControlName=”password” placeholder=”Password”>
<button (click)=”onSubmit()”>Submit</button>
</form>
`,
})
export class AppComponent {
myForm = new FormGroup({
username: new FormControl(”),
password: new FormControl(”)
});
constructor(private http: HttpClient) {}
onSubmit() {
const formValue = JSON.stringify(this.myForm); // this will cause the circular reference error
// const formValue = JSON.stringify(this.myForm.value); // this will correctly stringify only the form values
this.http.post(‘https://example.com/api’, formValue).subscribe(response => {
console.log(response);
});
}
}
To fix the error in the code above, update the “onSubmit()” method to the following:
// FIX: Extract only the necessary data
const formValue = JSON.stringify(this.myForm.value);
this.http.post(‘https://example.com/api’, formValue).subscribe(response => {
console.log(response);
});
}
– Allow the “Request” Module to “Stringify” Your Object
You can solve the “TypeError: Converting circular structure to JSON Nodejs” error if the “request” module can “stringify” your object. For example, the following code is using “JSON.stringify()” on the “request” object that is circular.
first_name: firstname,
last_name: lastname,
};
request.post(
{ url: “http://your_fancy_url/endpoint”, JSON: form_data },
function (err, connection, body) {}
);
exports.Register = function (request, response) {
response.header(“Access-Control-Allow-Origin”, “*”);
console.log(“Data” + JSON.stringify(request)); // The cause of the error.
};
Now, to allow the “request” module to do the “stringify” for us, we can update the previous code to the following. Here, it’s the “json: true” in the “options” that tells the “request” module to automatically convert the request body to JSON.
const form_data = {
first_name: firstname,
last_name: lastname,
};
const options = {
url: “http://your_fancy_url/endpoint”,
json: true,
body: form_data,
};
request.post(options, function (error, response, body) {
if (error) {
console.error(error);
} else {
console.log(body);
}
});
– Use a Serializer Function That Can Handle Circular Objects
A serializer function that filters out objects with circular references can solve the “TypeError: Converting circular structure to JSON Jest error. This will happen if you’re testing an object with circular references, and the following code is an example. In the code, the “actual” object returned by “getNestedObject” will contain circular references that will cause the following to fail: “expect(actual).toEqual(expected)”.
const obj = { prop1: ‘value1’, prop2: ‘value2’ };
obj.circularRef = obj;
obj.nested = { prop3: ‘value3’, prop4: ‘value4’ };
obj.nested.circularRef = obj;
return obj;
}
describe(‘getNestedObject’, () => {
test(‘returns a nested object with circular references’, () => {
const expected = {
prop1: ‘value1’,
prop2: ‘value2’,
circularRef: expect.any(Object),
nested: {
prop3: ‘value3’,
prop4: ‘value4’,
circularRef: expect.any(Object),
},
};
const actual = getNestedObject();
expect(actual).toEqual(expected);
});
});
The fix is to place a custom serializer as the first thing in “getNestedObject” and update the “expect” statements. Now, add the following serializer to the code above:
describe(‘getNestedObject’, () => {
// Fix_1: Add the custom serializer.
// Note, you can use a similar serializer to
// solve the __TypeError: Converting circular structure to JSON Express__ error
const customSerializer = (value) => {
if (typeof value === ‘object’ && value !== null) {
if (visitedObjects.indexOf(value) !== -1) {
return ‘[Circular]’;
}
visitedObjects.push(value);
}
return value;
};
let visitedObjects;
beforeEach(() => {
visitedObjects = [];
});
// Don’t forget the object that you want to
// test.
// Fix_2: Update “expect” statements.
expect(actual).toEqual(expected);
expect(actual).toMatchSnapshot({
circularRef: customSerializer,
‘nested.circularRef’: customSerializer,
});
});
});
Conclusion
This article explains the causes and solutions to “TypeError converting circular structure to JSON” in JavaScript. Now, the following will reinforce what you’ve learned so far, and help you in your future projects:
- The “TypeError Converting circular structure to JSON” occurs because your object has circular references.
- The root cause of the circular references error is when “JSON.stringify()” tries to serialize an object with circular references.
- To fix the “TypeError” when converting circular structures, use a custom serializer or the “flatted” package from Node Package Manager (npm).
Thank you for making it this far, we hope that you have a solution that works for you. Now, you can continue coding your next big application!
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team