For example, this code:
var a = {};
a.a = a;
JSON.stringify(a);
Will throw:
开发者_C百科TypeError: Converting circular structure to JSON
My question is, how to detect a circular structure?
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.
Here is function using native JSON detection
function isCircular (d) {
try {JSON.stringify(d)}
catch (e) {return true}
return false
}
精彩评论