xzz2021
发布于 2024-02-03 / 1 阅读
0
0

JSON.stringify打印循环引用的object对象报错

JSON.stringify打印循环引用的object对象报错

循环引用的obj数据,如果直接打印就是空,使用JSON转换打印会报错无法转换

Converting circular structure to JSON --> starting at object with constructor 'Socket'

  1. 临时处理方案,覆写JSON的stringify方法再使用,引用数据会变成"client":"[Circular socket]"

    var handleCircular = function() {
    var cache = [];
    var keyCache = []
    return function(key, value) {
    if (typeof value === 'object' && value !== null) {
    var index = cache.indexOf(value);
    if (index !== -1) {
    return '[Circular ' + keyCache[index] + ']';
    }
    cache.push(value);
    keyCache.push(key || 'root');
    }
    return value;
    }
    }

var tmp = JSON.stringify;
JSON.stringify = function(value, replacer, space) {
replacer = replacer || handleCircular();
return tmp(value, replacer, space);
}


评论