添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

The “ TypeError: Converting circular structure to JSON ” error occurs when attempting to stringify objects with circular references using JSON.stringify() . We’ll see the reasons for this error and various solutions to handle circular structures during JSON serialization.

What is TypeError: Converting circular structure to JSON?

The “ TypeError: Converting circular structure to JSON ” error occurs when attempting to stringify an object with circular references using JSON.stringify() . JSON format does not support circular structures, so this error indicates that the serialization process cannot handle the circular references within the object being converted to JSON .

Error:

Error-min

Why does “TypeError: Converting circular structure to JSON” occur?

Below, are the reasons for “TypeError: Converting circular structure to JSON” occurring:

  • Circular Reference in Object or Array
  • Circular Reference in Class

Reason 1: Circular Reference in Object or Array

In this scenario, a circular reference is created within the object obj, where the obj.circular property points back to the obj itself. When attempting to convert obj to JSON using JSON.stringify , the error “ TypeError: Converting circular structure to JSON ” occurs because JSON does not support circular references by default.

Example: The below code will generate the “ TypeError: Converting circular structure to JSON ” error.

JavaScript
const obj = {};
obj.circular = obj;
const jsonString = JSON.stringify(obj);

Output:

Hangup (SIGHUP)
/home/guest/sandbox/Solution.js:3
const jsonString = JSON.stringify(obj); // Error occurs here
^

TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Object'
--- property 'circular' closes the circle
at JSON.stringify (<anonymous>)
at Object.<anonymous> (/home/guest/sandbox/Solution.js:3:25)
at Module._compile (node:internal/modules/cjs/loader:1198:14)
at Object.Module._extensions..js (node:inte...

Reason 2: Circular Reference in Class

In this scenario, a circular reference is created within the errorClass constructor, where the this.self property points back to the errorClass instance itself. When attempting to stringify obj using JSON.stringify, the error “TypeError: Converting circular structure to JSON” occurs because JSON serialization does not handle circular references automatically in class instances.

Example: The below code will generate the “TypeError: Converting circular structure to JSON” error.

JavaScript
class errorClass {
    constructor() {
        this.self = this;
const obj = new errorClass();
JSON.stringify(obj); 

Output:

Hangup (SIGHUP)
/home/guest/sandbox/Solution.js:7
JSON.stringify(obj);
^

TypeError: Converting circular structure to JSON
--> starting at object with constructor 'errorClass'
--- property 'self' closes the circle
at JSON.stringify (<anonymous>)
at Object.<anonymous> (/home/guest/sandbox/Solution.js:7:6)
at Module._compile (node:internal/modules/cjs/loader:1198:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1252:10)
at Module.load (node:i...

Methods to solve “TypeError: Converting circular structure to JSON

Below are the solution for “TypeError: Converting circular structure to JSON”:

  • Use a replacer function to handle circular references
  • Implementing Custom toJSON method in Class

Solution 1: Use a replacer function to handle circular references

In this solution, a replacer function is used in JSON.stringify to handle circular references. The function checks if a value is an object and not null, then replaces circular references with a placeholder value (‘circular reference’). This prevents the “TypeError: Converting circular structure to JSON” error by handling circular structures during the JSON stringify operation.

Example: The below code will solve the “TypeError: Converting circular structure to JSON” error.

JavaScript
const obj = {};
obj.circular = obj;
const res = JSON.stringify(obj, (key, value) => {
    if (typeof value === 'object' && value !== null) {
        if (value instanceof Array) {
            return value.map(
                (item, index) => 
                (index === value.length - 1 ? 
                    'circular reference' : item));
        return { ...value, circular: 'circular reference' };
    return value;
console.log(res);

Output
{"circular":"circular reference"}

Solution 2: Implementing Custom toJSON method in Class

In this solution, we are implementing a custom toJSON method in the errorClass to handle the circular reference scenario. This custom method returns a JSON object with a placeholder value (‘[Circular Reference]‘) for the circularly referenced property, allowing JSON.stringify to serialize the object without giving the error.

Example: The below code will solve the “TypeError: Converting circular structure to JSON” error.

JavaScript
class errorClass {
    constructor() {
        this.self = this;
    toJSON() {
        return { self: '[Circular Reference]' };
const obj = new errorClass();
const res = JSON.stringify(obj);
console.log(res);

Output
{"self":"[Circular Reference]"}
                
How to print a circular structure in a JSON like format using JavaScript ?
The circular structure is when you try to reference an object which directly or indirectly references itself. Example: A -&gt; B -&gt; A OR A -&gt; A Circular structures are pretty common while developing an application. For Example, suppose you are developing a social media application where each user may have one or more images. Each image may be
Converting JSON text to JavaScript Object
Pre-requisite: JavaScript JSON JSON (JavaScript Object Notation) is a lightweight data-interchange format. As its name suggests, JSON is derived from the JavaScript programming language, but it’s available for use by many languages including Python, Ruby, PHP, and Java and hence, it can be said as language-independent. For humans, it is easy to rea
JavaScript TypeError - Reduce of empty array with no initial value
This JavaScript exception reduce of empty array with no initial value occurs if a reduce function is used with the empty array. Message: TypeError: reduce of empty array with no initial value Error Type: TypeError Cause of Error: This error is raised if an empty array is provided to the reduce() method because no initial value can be returned in th
JavaScript TypeError - "X" has no properties
This JavaScript exception null (or undefined) has no properties that occur if there is an attempt to access properties of null and undefined. They don't have any such properties. Message: TypeError: Unable to get property {x} of undefined or null reference (Edge) TypeError: null has no properties (Firefox) TypeError: undefined has no properties (Fi
JavaScript TypeError - "X" is (not) "Y"
This JavaScript exception X is (not) Y occurs if there is a data type that is not expected there. Unexpected is undefined or null values. Message: TypeError: Unable to get property {x} of undefined or null reference (Edge) TypeError: "x" is (not) "y" (Firefox) Few example are given below: TypeError: "x" is undefined TypeError: "y" is null TypeError
JavaScript TypeError - "X" is not a constructor
This JavaScript exception is not a constructor that occurs if the code tries to use an object or a variable as a constructor, which is not a constructor. Message: TypeError: Object doesn't support this action (Edge) TypeError: "x" is not a constructor TypeError: Math is not a constructor TypeError: JSON is not a constructor TypeError: Symbol is not
JavaScript TypeError - "X" is not a function
This JavaScript exception is not a function that occurs if someone trying to call a value from a function, but in reality, the value is not a function. Message: TypeError: Object doesn't support property or method {x} (Edge) TypeError: "x" is not a function Error Type: TypeError Cause of Error: There is an attempt to call a value from a function, b
JavaScript TypeError - "X" is not a non-null object
This JavaScript exception is not a non-null object that occurs if an object is not passed where it is expected. So the null is passed which is not an object and it will not work. Message: TypeError: Invalid descriptor for property {x} (Edge) TypeError: "x" is not a non-null object (Firefox) TypeError: Property description must be an object: "x" (Ch
JavaScript TypeError - "X" is read-only
This JavaScript exception is read-only works in strict mode-only and It occurs if a global variable or object property which has assigned to a value, is a read-only property. Message: TypeError: Assignment to read-only properties is not allowed in strict mode (Edge) TypeError: "x" is read-only (Firefox) TypeError: 0 is read-only (Firefox) TypeError
JavaScript TypeError - More arguments needed
This JavaScript exception more arguments needed occurs if there is an error in the way of function is called. If a few arguments are provided then more arguments need to be provided. Message: TypeError: argument is not an Object and is not null (Edge) TypeError: Object.create requires at least 1 argument, but only 0 were passed TypeError: Object.se
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Got It !
Please go through our recently updated Improvement Guidelines before submitting any improvements.
This article is being improved by another user right now. You can suggest the changes for now and it will be under the article's discussion tab.
You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!
Please go through our recently updated Improvement Guidelines before submitting any improvements.
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.