converting circular structure to json

Converting Circular Structure to JSON

Have you ever encountered an error message in JavaScript that says "Converting circular structure to JSON"? This error occurs when trying to convert an object that contains circular references, such as when an object references itself in a nested property or when two objects reference each other.

Why Does This Happen?

When converting an object to JSON, the JSON.stringify() function uses the JSON format to represent the object's properties and their values as a string. However, if the object contains circular references, the function cannot convert it to JSON because it would result in an infinite loop.

How to Fix It?

Here are some ways to fix this error:

  • Remove Circular References: The easiest way to fix this error is to remove the circular references from the object. This can be done by either removing the property that causes the circular reference or by restructuring the object so that it does not contain circular references.
  • Use a Custom Replacer Function: Another solution is to use the replacer parameter of the JSON.stringify() function to define a custom replacer function that can handle circular references. This function should check whether a value is a circular reference and replace it with a placeholder value that can be later replaced with the original circular reference.
  • Use a Third-Party Library: There are several third-party libraries available that can handle circular references when converting an object to JSON, such as circular-json and flatted. These libraries provide a simple way to convert objects with circular references without encountering the "Converting circular structure to JSON" error.

Example Code


const obj = {
  prop1: 'value1',
  prop2: {
    nestedProp: 'nestedValue',
    selfReference: null
  }
};

obj.prop2.selfReference = obj.prop2;

// This will throw an error
JSON.stringify(obj);

// Fix 1: Remove the Circular Reference
obj.prop2.selfReference = null;

// This will work
JSON.stringify(obj);

// Fix 2: Use a Custom Replacer Function
const replacer = (key, value) => {
  if (key === 'selfReference') {
    return '[Circular]';
  }
  return value;
};

const jsonString = JSON.stringify(obj, replacer);

// Fix 3: Use a Third-Party Library
const circularJSON = circularJson.stringify(obj);

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe