How to Print a Circular Structure in a JSON-like Format
In this JavaScript tutorial, you will find useful information about the method that is used to format an object to JSON what contains circular structure.
A circular reference exists in the JavaScript object being converted, not in the JSON format itself. It occurs when an object contains a property that references itself or another object that eventually points back to it.
You can safely convert such objects to JSON using JSON.stringify with a custom replacer function. The original attempt in this tutorial contained invalid syntax and would throw a ReferenceError. Even with correct syntax, a naive replacer often fails to properly manage the cache, leading to memory leaks or incorrect output. The following ES6 utility function correctly tracks visited objects to prevent infinite loops:
JavaScript: Circular structure in a JSON-like format
Note that this replacer discards duplicate object references. Depending on your use case, you might prefer to replace them with a placeholder string instead of undefined.
The JSON.stringify() Method
The <kbd class="highlighted">JSON.stringify()</kbd> method is used for converting a JavaScript object or value to a JSON format, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
Replacer is a function that modifies the behaviour of the stringification process, or an array of string and number objects. If the value of replacer is null or not given, all object's properties are included in the resulting JSON string.