8

For example, this code:

var a = {};
a.a = a;
JSON.stringify(a);

Will throw:

TypeError: Converting circular structure to JSON

My question is, how to detect a circular structure?

  • What do you mean by "detecting"? In this it is pretty obvious since there is the same var before and after the `=` – gnur Mar 03 '11 at 15:46
  • 6
    gnur: He means, given an arbitrary data structure, determine if it's cyclic. – erjiang Mar 03 '11 at 15:48
  • You can also take a look at the [answer I posted to similar question](http://stackoverflow.com/a/15179204/592253) which gives an example and a link a jsfiddle where you can test it. – Xotic750 Mar 02 '13 at 20:41
  • I came across this error using `express` in `node` where i did this for testing purposes: `res.send(req)` or `res.json(req)`. I was trying to send back the initial request as the response - I don't know enough about express to know why this was an invalid action or what a valid alternative would be. – user1063287 May 15 '18 at 12:58

2 Answers2

9

Crockford's JSON implementation does just that. It looks like it just keeps a list while traversing the object graph. The code is fairly easy to follow.

Ken
  • 1,159
  • 1
  • 9
  • 13
  • 5
    I still cannot stand how Crockford left-aligns all comments in his code. I find it so hard to follow jumping left as I read the code top-down. – Roatin Marth Mar 03 '11 at 15:56
  • 1
    @RoatinMarth: on the contrary, it allows me to focus on the code when I read the code; and when I read the documentation, I don’t need to read the code. Comments pertaining to the code itself are placed with the code itself. – Martijn Mar 03 '11 at 16:01
  • 1
    Roatin: So paste it in your editor, select all, indent-region. Why is this worth complaining about? You could have fixed it faster than writing that comment. – Ken Mar 04 '11 at 06:28
  • @Ken that function is bullcrap. Try retrocycling the global object in NodeJS it'll get you a nice sweet range error (maximum call stack exceeded). – Silviu-Marian Jun 27 '12 at 10:50
4

Here is function using native JSON detection

function isCircular (d) {
  try {JSON.stringify(d)}
  catch (e) {return true}
  return false
}
Afanasii Kurakin
  • 3,330
  • 2
  • 24
  • 26