开发者

How to detect circular structures?

开发者 https://www.devze.com 2023-02-14 19:56 出处:网络
For example, this code: var a = {}; a.a = a; JSON.stringify(a); Will throw: 开发者_C百科 TypeError: Converting circular structure to JSON

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消