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

Posted . Visible to the public.

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;

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.

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2014-10-29 08:35)