Published on

Handling Circular References in JSON.stringify in JavaScript


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;


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.


npm install @sindresorhus/safe-stringify


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

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

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

Happy serializing Objects!