在使用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