在使用JSON.stringify方法去转化成字符串,会报错TypeError: Converting circular structure to JSON
原因: 对象中有对自身的循环引用;
例如:
let test = { a: 1, b: 2 };
test.c = test; // 循环引用
JSON.stringify(test); // 报错
解决方法:
下面的 json_str 就是JSON.stringify 转换后的字符串
var cache = [];
var json_str = JSON.stringify(json_data, function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
return;
}
cache.push(value);
}
return value;
});
cache = null; //释放cache
解决啦!
参考:https://blog.csdn.net/g401946949/article/details/101757165
当JSON.stringify遇到对象中存在循环引用时,会导致TypeError。解决方法是使用一个缓存数组来跟踪已序列化的对象,避免重复序列化。通过检查value是否已经在缓存中,若在则忽略,从而成功转换。
5660

被折叠的 条评论
为什么被折叠?



