gpt4 book ai didi

javascript - 如何在JSON.stringify : Uncaught TypeError: Converting circular structure to JSON?中找到循环结构

转载 作者:数据小太阳 更新时间:2023-10-29 05:23:04 25 4
gpt4 key购买 nike

当我在大型结构上遇到 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);
}
}
}

它所做的是在遍历 JSON 树(可能是树 :))时收集已访问的属性的名称,一旦 JSON.stringify 检测到循环引用并抛出,“堆栈”变量将包含其中的踪迹它正在遍历的子树。并将此路径记录到控制台。

但是,这不是经过严格测试的解决方案。

关于javascript - 如何在JSON.stringify : Uncaught TypeError: Converting circular structure to JSON?中找到循环结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20953383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com