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

Viewed 873518

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?

Thanks.

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

I want to stringify obj into:

{"a":"foo"}
31 Answers

I wonder why nobody posted the proper solution from MDN page yet...

const circularReference = {otherData: 123}
circularReference.myself = circularReference

const getCircularReplacer = () => {
  const seen = new WeakSet()
  return (key, value) => {
    if (typeof value === "object" && value !== null) {
      if (seen.has(value)) {
        return
      }
      seen.add(value)
    }
    return value
  }
}

const stringified = JSON.stringify(circularReference, getCircularReplacer())

console.log(stringified)

Seen values should be stored in a set, not in array (replacer gets called on every element) and there is no need to try JSON.stringify each element in the chain leading to a circular reference.

Like in the accepted answer, this solution removes all repeating values, not just the circular ones. But at least it does not have exponential complexity.

@RobW's answer is correct, but this is more performant ! Because it uses a hashmap/set:

const customStringify = function (v) {
  const cache = new Set();
  return JSON.stringify(v, function (key, value) {
    if (typeof value === 'object' && value !== null) {
      if (cache.has(value)) {
        // Circular reference found
        try {
          // If this value does not reference a parent it can be deduped
         return JSON.parse(JSON.stringify(value));
        }
        catch (err) {
          // discard key if value cannot be deduped
         return;
        }
      }
      // Store value in our set
      cache.add(value);
    }
    return value;
  });
};

The second argument to JSON.stringify() also allows you to specify an array of key names that should be preserved from every object it encounters within your data. This may not work for all use cases, but is a much simpler solution.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

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

var json = JSON.stringify(obj, ['a']);
console.log(json);
// {"a":"foo"}

Note: Strangely, the object definition from OP does not throw a circular reference error in the latest Chrome or Firefox. The definition in this answer was modified so that it did throw an error.


This code will fail for circular reference:

    JSON.stringify(circularReference);
// TypeError: cyclic object value

Use the below code:

 const getCircularReplacer = () => {
  const seen = new WeakSet();
  return (key, value) => {
    if (typeof value === "object" && value !== null) {
      if (seen.has(value)) {
        return;
      }
      seen.add(value);
    }
    return value;
  };
};

JSON.stringify(circularReference, getCircularReplacer());

To update the answer of overriding the way JSON works (probably not recommended, but super simple), don't use circular-json (it's deprecated). Instead, use the successor, flatted:

https://www.npmjs.com/package/flatted

Borrowed from the old answer above from @user1541685 , but replaced with the new one:

npm i --save flatted

then in your js file

const CircularJSON = require('flatted');
const json = CircularJSON.stringify(obj);

Try this:

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

var circular_replacer = (value) => {
    var seen = [];
    if (value != null && typeof value == "object") {
        if (seen.indexOf(value) >= 0) return;
        seen.push(value);
    }
    return value;
};

obj = circular_replacer(obj);

Although this has been answered sufficiently, you could also explicitly delete the property in question before stringification using the delete operator.

delete obj.b; 
const jsonObject = JSON.stringify(obj);

delete operator

this will remove the need to build or maintain complex logic to remove circular references.

function myStringify(obj, maxDeepLevel = 2) {
  if (obj === null) {
    return 'null';
  }
  if (obj === undefined) {
    return 'undefined';
  }
  if (maxDeepLevel < 0 || typeof obj !== 'object') {
    return obj.toString();
  }
  return Object
    .entries(obj)
    .map(x => x[0] + ': ' + myStringify(x[1], maxDeepLevel - 1))
    .join('\r\n');
}

Most of the answers in this thread are catered to use with JSON.stringify specifically -- they do not show how to actually remove circular-references in the original object-tree. (well, short of calling JSON.parse again afterward -- which requires reassignment, and has a higher performance impact)

For removing circular-references from the source object-tree, you can use a function such as this: https://stackoverflow.com/a/63952549/2441655

These general-purpose circular-reference-remover functions can then be used to make subsequent calls to circular-reference-sensitive functions (like JSON.stringify) safe:

const objTree = {normalProp: true};
objTree.selfReference = objTree;
RemoveCircularLinks(objTree); // without this line, the JSON.stringify call errors
console.log(JSON.stringify(objTree));

Here's a solution that:

  • removes cycles only (and not all duplicate object references, as do most of the solutions posted here so far),
  • is not unnecessarily verbose,
  • is fast,
  • does not require any library dependency.
function replaceCycles(obj, replacement = undefined, seen = new WeakSet()) {
  if (typeof obj === 'object')
    if (seen.has(obj))
      return replacement 
    else {
      seen.add(obj)
      const newObj = {}
      for (const key in obj)
        newObj[key] = replaceCycles(obj[key], replacement, seen)
      seen.delete(obj)
      return newObj
    }
  else
    return obj
}

Usage:

const a = {
  b: 'v1',
  c: {
    d: 'v2'
  }
}

a.e = a.c
a.c.f = a.c

console.log(JSON.stringify(replaceCycles(a, '[CYCLE]')))

Output:

"{'b':'v1','c':{'d':'v2','f':'[CYCLE]'},'e':{'d':'v2','f':'[CYCLE]'}}"

You could try the JSON parser library: treedoc. it supports circular references and also dedupes the repeated objects with references.

yarn add treedoc

import {TD} from 'treedoc'
TD.stringify(obj);

If you want more customization

import {TD, TDEncodeOption} from 'treedoc'

const opt = new TDEncodeOption();
opt.coderOption.setShowType(true).setShowFunction(true);
opt.jsonOption.setIndentFactor(2);
return TD.stringify(obj, opt);

The generated JSON file can be viewed by the viewer http://treedoc.org, which supports the navigation through JSON node references.

[shameless plug] I'm the author of this library

We use object-scan for our data processing and it might be a viable solution here. This is how it could work (also pruning arrays correctly)

.as-console-wrapper {max-height: 100% !important; top: 0}
<script type="module">
import objectScan from 'https://cdn.jsdelivr.net/npm/object-scan@18.1.2/lib/index.min.js';

const prune = (data) => objectScan(['**'], {
  rtn: 'count',
  filterFn: ({ isCircular, parent, property }) => {
    if (isCircular) {
      if (Array.isArray(parent)) {
        parent.splice(property, 1);
      } else {
        delete parent[property];
      }
      return true;
    }
    return false;
  },
  breakFn: ({ isCircular }) => isCircular === true
})(data);

const obj = { a: 'foo', c: [0] };
obj.b = obj;
obj.c.push(obj);
console.log(obj);
// => <ref *1> { a: 'foo', c: [ 0, [Circular *1] ], b: [Circular *1] }

console.log(prune(obj)); // returns circular counts
// => 2

console.log(obj);
// => { a: 'foo', c: [ 0 ] }
</script>

Disclaimer: I'm the author of object-scan

I created following method for my LoggingUtilities class. Following method takes source and target objects, and assign source to target by given maxLevel.

  static assignObjectByLevel(
    sourceObject: any,
    targetObject: any,
    currentLevel: number = 0,
    maxLevel: number = 3,
    showUndefinedValues = false
  ): any {
    if (currentLevel >= maxLevel) {
      return;
    }

    const objQueue = [];
    for (const key in sourceObject) {
      if (sourceObject.hasOwnProperty(key)) {
        const value = sourceObject[key];
        if (typeof value === "object") {
          objQueue.push({ key, value });
        } else {
          targetObject[key] = value;
        }
      } else {
        if (showUndefinedValues) {
          targetObject[key] = "undefined/null";
        }
      }
    }

    while (objQueue.length > 0) {
      const objVal = objQueue.pop();
      currentLevel++;
      targetObject[objVal.key] = {};
      this.assignObjectByLevel(
        objVal.value,
        targetObject[objVal.key],
        currentLevel,
        maxLevel,
        false
      );
    }
  }

Usage Example:

   const logObjParam = {
      level1: "value1",
      level2: {
        value2: "value2",
        level3: {
          value3: "value3",
          level4: {
            value4: " value4",
            level5: {
              value5: " value5",
            },
          },
        },
      },
    };

 let logObj = {};
 this.assignObjectByLevel(logObjParam, logObj);

Result:

{
  "level1": "value1",
  "level2": {
    "value2": "value2",
    "level3": {
      "value3": "value3",
      "level4": {}
    }
  }
}

superserial fully serializes JavaScript objects.

https://github.com/denostack/superserial

Usage:

const serializer = new Serializer();

const nodes = [{ self: null as any, siblings: [] as any[] }, {
  self: null as any,
  siblings: [] as any[],
}];
nodes[0].self = nodes[0];
nodes[0].siblings = nodes;
nodes[1].self = nodes[1];
nodes[1].siblings = nodes;

const serialized = serializer.serialize(nodes);

console.log(serialized);

output:

[$1,$2];{"self":$1,"siblings":$0};{"self":$2,"siblings":$0}

This solution fixes the issue reported by user2451227 on accepted answer (when o = {}; JSON.stringify([o, o], getCircularReplacer())).

function newCircularReplacer () {
  const seenValues = []
  return circularReplacer

  function circularReplacer (key, value) {
    if (typeof value === 'object' && value !== null && Object.keys(value).length) {
      const stackSize= seenValues.length
      if (stackSize) {
        for (let n = stackSize - 1; seenValues[n][key] !== value; --n)
          seenValues.pop() // clean up expired references
        if (seenValues.includes(value)) return '[Circular]'
      }
      seenValues.push(value)
    }
    return value
  }
}

let o = {a: 1}
o.b = o // Circular reference
console.log(
  JSON.stringify(o, newCircularReplacer()) // {a:1,b:[Circular]} ✅
)

o = {}
a = [o, o] // NOT circular reference
console.log(
  JSON.stringify(a, newCircularReplacer()) // [{},{}] ✅
)

Related