How can I print a circular structure in a JSON-like format?


I have a big object I want to convert to JSON and send. However it has circular structure. I want to toss whatever circular references exist and send whatever can be stringified. How do I do that?


var obj = {
  a: "foo",
  b: obj

I want to stringify obj into:

7/9/2019 7:29:15 AM

Accepted Answer

Use JSON.stringify with a custom replacer. For example:

// Demo: Circular reference
var o = {};
o.o = o;

// Note: cache should not be re-used by repeated calls to JSON.stringify.
var cache = [];
JSON.stringify(o, function(key, value) {
    if (typeof value === 'object' && value !== null) {
        if (cache.indexOf(value) !== -1) {
            // Duplicate reference found, discard key
        // Store value in our collection
    return value;
cache = null; // Enable garbage collection

The replacer in this example is not 100% correct (depending on your definition of "duplicate"). In the following case, a value is discarded:

var a = {b:1}
var o = {}; = a;
o.two = a;
// one and two point to the same object, but two is discarded:
JSON.stringify(o, ...);

But the concept stands: Use a custom replacer, and keep track of the parsed object values.

6/7/2019 8:49:51 PM

In Node.js, you can use util.inspect(object). It automatically replaces circular links with "[Circular]".

Albeit being built-in (no installation is required), you must import it

import * as util from 'util' // has no default export
import { inspect } from 'util' // or directly
// or 
var util = require('util')
To use it, simply call

Also be aware that you can pass options object to inspect (see link above)

inspect(myObject[, options: {showHidden, depth, colors, showProxy, ...moreOptions}])

Please, read and give kudos to commenters below...

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow