我有一个节点数组。 每个节点都有一个子节点数组和一个指向其父节点的指针。 我想使用 JSON.stringify 序列化它,但使用父指针显然会导致循环引用,并且 JSON 会引发异常。我可以做些什么来解决循环引用并使用 JSON 进行序列化?
相关问题:Chrome sendrequest error: TypeError: Converting circular structure to JSON
最佳答案
您应该在具有父级的对象中创建自定义的 toJson 函数。
If an object being stringified has a property named toJSON whose value is a function, then the toJSON method customizes JSON stringification behavior
var x = {
foo: 'foo',
toJSON: function () {
return 'bar';
}
};
var json = JSON.stringify({x: x});
那么您可以在具有父引用的对象中创建该函数,也许像这样?
MyObj = function(){
this.xxx = 'foobar';
this.zzz = 'foooobar';
this.name = 'foo';
this.parent = ...;
toJSON = function(){
tmp = '{'
for(prop in MyObj){
if(prop == 'parent'){
tmp += 'parent: "'+ this['parent'].name +'"'; //maybe?? optional!
}else{
tmp += prop + ':' + this[prop].stringify + ','; //you will still use the browser function
}
tmp += '}
}
return tmp;
}
}
关于javascript - 使用 JSON 序列化图论树的解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12151118/