How to print a circular structure in a JSON like format using JavaScript ?
Last Updated :
09 Feb, 2021
The circular structure is when you try to reference an object which directly or indirectly references itself.
Example:
A -> B -> A OR A -> 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 referencing its owner. Something like this:
{
User1: {
Image1:{
URL: 'Image Url',
Owner: User1 (object)
},
Image2:{
URL: 'Image Url',
Owner: User1 (object)
}
}
}
Here you can easily resolve this by passing the user id to Owner instead of the user object.
Passing such objects to JSON.stringify() results in 'Converting circular structure to JSON Error'.
Let's take an example and try to resolve this issue.
Example:
JavaScript
var object = {};
object.array = {'first':1};
object.array2 = object;
console.log(object);
The output should look something like this:
If we pass the above object to JSON.stringify() then this will result in the following error:
To resolve this we can pass another parameter to JSON.stringify() which is actually a function. And we can handle the object however we want inside the function. It takes two parameters, the key and the value that is being stringified. It gets called for each property on the object or array being stringified. It should return the value that should be added to the JSON string.
Let's create a function named circularReplacer.
const circularReplacer = () => {
// Creating new WeakSet to keep
// track of previously seen objects
const seen = new WeakSet();
return (key, value) => {
// If type of value is an
// object or value is null
if (typeof(value) === "object"
&& value !== null) {
// If it has been seen before
if (seen.has(value)) {
return;
}
// Add current value to the set
seen.add(value);
}
// return the value
return value;
};
};
Explanation:
- The above function will first create a WeakSet to keep track of previously seen objects. WeakSet in JavaScript is used to store a collection of objects. It adapts the same properties of that of a set i.e. does not store duplicates. Read more above WeakSet here.
- Checks if the type of value is an object and the value is not null. Then checks if it has been seen before. If yes then just return. if not then add it to the set.
- Instead of just return nothing when an object has been seen. We can return even more useful information, for example, return 'Object', which will tell us that value of this will create a circular structure.
- If the type of value is not an object or the value is null. Then simply return the value.
Example 1:
JavaScript
var object = {};
object.array = {'first':1};
object.array2 = object;
const circularReplacer = () => {
// Creating new WeakSet to keep
// track of previously seen objects
const seen = new WeakSet();
return (key, value) => {
// If type of value is an
// object or value is null
if (typeof(value) === "object"
&& value !== null) {
// If it has been seen before
if (seen.has(value)) {
return;
}
// Add current value to the set
seen.add(value);
}
// return the value
return value;
};
};
var jsonString = JSON.stringify(
object, circularReplacer());
console.log(jsonString);
Output:
Note: If we just return when seeing a circular structure that key will not get added to the output string.
Example 2: Let's return a string instead of nothing.
JavaScript
var object = {};
object.array = {'first':1};
object.array2 = object;
object.array3 = object.array2;
const circularReplacer = () => {
// Creating new WeakSet to keep
// track of previously seen objects
const seen = new WeakSet();
return (key, value) => {
// If type of value is an
// object or value is null
if (typeof(value) === "object"
&& value !== null) {
// If it has been seen before
if (seen.has(value)) {
return 'Object';
}
// Add current value to the set
seen.add(value);
}
// return the value
return value;
};
};
var jsonString = JSON.stringify(
object, circularReplacer());
console.log(jsonString);
Output:
Similar Reads
How to view array of a structure in JavaScript ? The Javascript arrays are heterogeneous. The structure of the array is the same which is enclosed between two square brackets [ ], and the string should be enclosed between either "double quotes" or 'single quotes'. You can get the structure of by using JSON.stringify() or not, here you will see the
3 min read
How to Recursively Build a JSON Tree Structure in JavaScript ? To create a JSON tree structure recursively in JavaScript we need to create a recursive function that traverses the data and constructs the tree. We can create a JSON tree structure recursively in JavaScript using the below methods. Table of Content Using Arrays to build a JSON tree structure Using
4 min read
How to Create an Array of Object Literals in a Loop using JavaScript? Creating arrays of object literals is a very frequent activity in JavaScript, as often when working with data structures, several objects are needed. This article will allow your hand through different ways of coming up with an array of object literals in a loop in JavaScript. Here are different app
5 min read
How to Convert a Map to JSON String in JavaScript ? A Map is a collection of key-value pairs, where each key is unique. In this article, we will see how to convert a Map to a JSON (JavaScript Object Notation) string in JavaScript. However, JSON.stringify() does not directly support Map objects. Table of ContentUsing Object.fromEntries() MethodUsing A
2 min read
How to Pretty Print JSON String in JavaScript? To pretty print JSON, you can format JSON strings with proper indentation, making them easy to read and debug. In JavaScript, you can achieve this using JSON.stringify() with optional parameters to specify the indentation level.Pretty printing JSON adds line breaks and spaces for readability.It is c
3 min read
How to Convert JSON to string in JavaScript ? In this article, we are going to learn the conversion of JSON to string in JavaScript. Converting JSON to a string in JavaScript means serializing a JavaScript object or data structure represented in JSON format into a textual JSON string for data storage or transmission.Several methods can be used
3 min read
How to JSON Stringify an Array of Objects in JavaScript ? In JavaScript, the array of objects can be JSON stringified for easy data interchange and storage, enabling handling and transmission of structured data. The below approaches can be utilized to JSON stringify an array of objects.Table of ContentUsing JSON.stringify with a Replacer Function Using a C
3 min read
How to Create an HTML Table from an Object Array Using JavaScript ? Tables are a fundamental part of web development, and displaying data in a structured manner is a common requirement. JavaScript provides a powerful way to dynamically generate HTML content, making it easy to create tables from object arrays. Table of Content Using innerHTML propertyUsing appendChil
2 min read
How to Convert String to JSON in JavaScript? In JavaScript, converting a string to JSON is important for handling data interchangeably between server and client, parsing external API responses, and storing structured data in applications. Below are the approaches to converting string to JSON in JavaScript: Table of Content Using JSON.parse()Us
2 min read
How to print the content of an object in JavaScript ? To print the content of an object in JavaScript we will use JavaScript methods like stringify, object.values and loops to display the required data. Let's first create a JavaScript Object containing some key-values as given below: JavaScript // Given Object const obj = { name: 'John', age: 30, city:
3 min read