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 money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
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)