How to detect circular patterns?

For example, this code:

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

Throws:

 TypeError: Converting circular structure to JSON 

My question is how to detect a circular structure?

+4
source share
2 answers

Crockford's JSON implementation does just that. It looks like it just saves the list when moving the graph of objects. The code is pretty simple.

+9
source

Here is a function using inline JSON detection

 function isCircular (d) { try {JSON.stringify(d)} catch (e) {return true} return false } 
+2
source

Source: https://habr.com/ru/post/1342144/


All Articles