问题描述
我有一个对象(解析树),它包含对其他节点的引用的子节点。
I have an object (parse tree) that contains child nodes which are references to other nodes.
我想使用 JSON.stringify()
序列化这个对象,但我得到: TypeError:循环对象值
因为我提到的结构。
I'd like to serialize this object, using JSON.stringify()
, but I get : TypeError: cyclic object value
because of the constructs I mentioned.
我怎么能解决这个问题?是否在序列化对象中表示了对其他节点的这些引用并不重要。
How could I work around this? It does not matter to me whether these references to other nodes are represented or not in the serialized object.
另一方面,当它们是对象时从这些属性中删除它们正在创建似乎很乏味,我不想对解析器(水仙)进行更改。
On the other hand, removing these properties from the object when they are being created seems tedious and I wouldn't want to make changes to the parser (narcissus).
推荐答案
使用第二个参数 stringify
,,以排除已经序列化的对象:
Use the second parameter of stringify
, the replacer function, to exclude already serialized objects:
var seen = [];
JSON.stringify(obj, function(key, val) {
if (val != null && typeof val == "object") {
if (seen.indexOf(val) >= 0) {
return;
}
seen.push(val);
}
return val;
});
正如其他评论中正确指出的那样,此代码会删除每个看到的对象,不仅是递归的。
As correctly pointed out in other comments, this code removes every "seen" object, not only "recursive" ones.
例如,对于:
a = {x:1};
obj = [a, a];
结果不正确。如果您的结构是这样的,Crockford的是一个更好的选择。
the result will be incorrect. If your structure is like this, Crockford's decycle is a better option.
这篇关于序列化包含循环对象值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!