Mic*_*arf 7 javascript json circular-reference
当我进入Uncaught TypeError: Converting circular structure to JSON一个大型结构时,很难找到圆形参考的确切位置.
有没有一种简单的方法来查找/调试数据结构中的循环元素?
我还没有找到一个简单的方法,其他人似乎建议在JSON.stringify中使用自定义替换函数来控制访问过哪些属性.
我试图写这样的替换者:
function detector(obj) {
function collector (stack, key, val) {
var idx = stack[stack.length - 1].indexOf(key);
try {
var props = Object.keys(val);
if (!props.length) throw props;
props.unshift({idx : idx});
stack.push(props);
} catch (e) {
while (!(stack[stack.length - 1].length - 2)) {
idx = stack[stack.length -1][0].idx;
stack.pop();
}
if (idx + 1) {
stack[stack.length - 1].splice(idx, 1);
}
}
return val;
}
var stack = [[]];
try {
JSON.stringify(obj, collector.bind(null, stack));
} catch (e) {
if (e.message.indexOf('circular') !== -1) {
var idx = 0;
var path = '';
var parentProp = '';
while(idx + 1) {
idx = stack.pop()[0].idx;
parentProp = stack[stack.length - 1][idx];
if (!parentProp) break;
path = '.' + parentProp + path;
}
console.log(path);
}
}
}
Run Code Online (Sandbox Code Playgroud)
它的作用是遍历JSON树(可能是树:))它收集已经访问过的属性的名称,一旦JSON.stringify检测到循环引用和抛出,'stack'变量将包含它的哪个子树的跟踪遍历.它将此路径记录到控制台.
但是,这不是经过严格测试的解决方案.
| 归档时间: |
|
| 查看次数: |
2474 次 |
| 最近记录: |