Published on

Handling Circular References in JSON.stringify in JavaScript

Authors

If your object has a circular dependency and you try to serialize it with JSON.stringify then it'll throw the following error.

const foo  = {};
foo.bar = foo;

JSON.stringify(foo)


/*
VM1188:4 Uncaught TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    --- property 'bar' closes the circle
    at JSON.stringify (<anonymous>)
    at <anonymous>:4:6
*/

For such use cases, safe-stringify might be a better choice.

How does it work?

It'll replace the circular references with [Circular] and because of that, you'll not be getting errors while serializing the object.

Dependency

npm install @sindresorhus/safe-stringify

Usage

import safeStringify from '@sindresorhus/safe-stringify';

const foo  = {example:"hello"};
foo.bar = foo;

console.log(safeStringify(foo)); // {"example":"hello","bar":"[Circular]"}

Happy serializing Objects!