“太多的递归”在具有循环依赖关系的大对象上调用JSON.stringify时出错 [英] "too much recursion" error when calling JSON.stringify on a large object with circular dependencies

查看:484
本文介绍了“太多的递归”在具有循环依赖关系的大对象上调用JSON.stringify时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含循环引用的对象,我想看看它的JSON表示。例如,如果我构建这个对象:

  var myObject = {member:{}}; 
myObject.member.child = {};
myObject.member.child.parent = myObject.member;

并尝试呼叫

  JSON.stringify(myObject的); 

我得到错误too recursion,这并不奇怪。 子对象有一个对父的引用,父对子有一个引用。 JSON表示并不一定非常准确,因为我只用它来进行调试,而不是将数据发送到服务器或将对象序列化到文件或类似的东西。有没有办法告诉JSON.stringify忽略某些属性(在这种情况下,子对象的属性),以便我得到:


$ b $

  {
member:{
child:{}
}
}

我能想到的最接近的是使用 getChild() getParent()方法,而不仅仅是成员,因为JSON.stringify忽略任何属性是函数,但我宁愿不这样做,

解决方案

您可以将函数作为第二个参数传递给stringify。
这个函数接收stringify成员的键和值作为参数。
如果这个函数返回undefined,那么这个成员将被忽略。

$ $ $ $ $ $ $ $ alert(JSON.stringify(myObject,function k,v){
return(k ==='member')?undefined:v;
}));

...或使用例如萤火虫或使用toSource() - 方法,如果你只想看看对象里面有什么。

  alert(myObject.toSource ()); 


I have an object that contains circular references, and I would like to look at the JSON representation of it. For example, if I build this object:

var myObject = {member:{}};
myObject.member.child = {};
myObject.member.child.parent = myObject.member;

and try to call

JSON.stringify(myObject);

I get the error "too much recursion", not surprisingly. The "child" object has a reference to its "parent" and the parent has a reference to its child. The JSON representation does not have to be perfectly accurate, as I'm only using it for debugging, not for sending data to a server or serializing the object into a file or anything like that. Is there a way to tell JSON.stringify to just ignore certain properties (in this case the parent property of the child object), so that I would get:

{
    "member" : {
        "child" : {}
    }
}

The closest I can think of is to use getChild() and getParent() methods instead of just members, because JSON.stringify ignores any properties that are functions, but I'd rather not do that if I don't have to.

解决方案

You can pass a function as the second argument to stringify. This function receives as arguments the key and value of the member to stringify. If this function returns undefined, the member will be ignored.

alert(JSON.stringify(myObject, function(k, v) {
    return (k === 'member') ? undefined : v;
}));

...or use e.g. firebug or use the toSource()-method, if you only want to see whats inside the object.

alert(myObject.toSource());

这篇关于“太多的递归”在具有循环依赖关系的大对象上调用JSON.stringify时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆