How to Print a Circular Structure in a JSON-like Format

The circular structure is not in JSON, but in the object that is being converted to JSON. The circular structure come from objects that contain something which references the original object.

To convert a circular structure to JSON format can be possible with JSON.stringify. Use it with a custom replacer like in this example:

Javascript circular structure in a JSON-like format
//Circular reference let circ = { a: 1 }; circ.a = circ; // Note that the cache should not be reused by repeated calls to JSON.stringify let cache = []; JSON.safeStringify = (circ, (key, val) => { if (typeof val === 'object' && val !== null) { // Duplicate reference found, reset key if (cache.includes(val)) return; // Save value in our collection cache.push(val); } return val; }); //cache = null; // Enable garbage collection console.log('cache', JSON.safeStringify(cache));

The replacer in the given example is not 100% correct which depends on your definition of "duplicate".

In this case, a value is discarded but it uses a custom replacer, and keep track of the parsed object values:

Javascript circular structure in a JSON-like format
let a = { b: 1 } let opt = {}; = a; opt.two = a; // one and two point to the same object, but two is discarded:JSON.stringify(opt, ...); //As an utility function written in ES6, use the following: // handles circular references safely JSON.safeStringify = (obj, indent = 2) => { let cache = []; const retVal = JSON.stringify( obj, (key, val) => typeof val === "object" && val !== null ? cache.includes(val) ? undefined // Duplicate reference found reset key : cache.push(val) && val // Store value in our collection : val, indent ); cache = null; return retVal; }; console.log('options', JSON.safeStringify(opt));

The JSON.stringify() Method

The JSON.stringify() 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.