Posted over 4 years ago. Visible to the public. Linked content.

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

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

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 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.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Arne Hartherz
Last edit:
over 4 years ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more