Read more

Dealing with "TypeError: Converting circular structure to JSON" on JavaScript

Arne Hartherz
October 29, 2014Software engineer at makandra GmbH

JavaScript structures that include circular references can't be serialized with a"plain" JSON.stringify. Example:

a = { name: 'Groucho' };
b = { name: 'Harpo', sibling: a };
a.sibling = b;
Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

Doing a JSON.stringify(a) will throw an error:

TypeError: Converting circular structure to JSON

There is not much you can do about that except specifying a custom serializer function that detects and cleans up circular references. There are existing solutions so you do not need to think of one yourself, like https://github.com/isaacs/json-stringify-safe Show archive.org snapshot .

You probably want to clean up that project's stringify.js a bit as just dropping it into your project would define some global methods. But you can easily wrap them into a custom class or AngularJS filter to stash them away.

For the above structure you will then get the following.

{"name":"Groucho","sibling":{"name":"Harpo","sibling":"[Circular ~]"}}

Note how [Circular ~] shows the path to the referenced object. In more deeply nested structures, you would see something like [Circular ~.rows.1].


Another good-looking solution is https://github.com/WebReflection/circular-json Show archive.org snapshot . It seems to offer a bit more, but json-stringify-safe just did enough for me -- which was inspecting a circular object structure via an AngularJS filter.

Posted by Arne Hartherz to makandra dev (2014-10-29 09:35)