这可以工作并告诉您哪些属性是循环的。它还允许使用引用重新构造对象
JSON.stringifyWithCircularRefs = (function() {
const refs = new Map();
const parents = [];
const path = ["this"];
function clear() {
refs.clear();
parents.length = 0;
path.length = 1;
}
function updateParents(key, value) {
var idx = parents.length - 1;
var prev = parents[idx];
if (prev[key] === value || idx === 0) {
path.push(key);
parents.push(value);
} else {
while (idx-- >= 0) {
prev = parents[idx];
if (prev[key] === value) {
idx += 2;
parents.length = idx;
path.length = idx;
--idx;
parents[idx] = value;
path[idx] = key;
break;
}
}
}
}
function checkCircular(key, value) {
if (value != null) {
if (typeof value === "object") {
if (key) { updateParents(key, value); }
let other = refs.get(value);
if (other) {
return '[Circular Reference]' + other;
} else {
refs.set(value, path.join('.'));
}
}
}
return value;
}
return function stringifyWithCircularRefs(obj, space) {
try {
parents.push(obj);
return JSON.stringify(obj, checkCircular, space);
} finally {
clear();
}
}
})();
删除大量噪音的例子:
{
"requestStartTime": "2020-05-22...",
"ws": {
"_events": {},
"readyState": 2,
"_closeTimer": {
"_idleTimeout": 30000,
"_idlePrev": {
"_idleNext": "[Circular Reference]this.ws._closeTimer",
"_idlePrev": "[Circular Reference]this.ws._closeTimer",
"expiry": 33764,
"id": -9007199254740987,
"msecs": 30000,
"priorityQueuePosition": 2
},
"_idleNext": "[Circular Reference]this.ws._closeTimer._idlePrev",
"_idleStart": 3764,
"_destroyed": false
},
"_closeCode": 1006,
"_extensions": {},
"_receiver": {
"_binaryType": "nodebuffer",
"_extensions": "[Circular Reference]this.ws._extensions",
},
"_sender": {
"_extensions": "[Circular Reference]this.ws._extensions",
"_socket": {
"_tlsOptions": {
"pipe": false,
"secureContext": {
"context": {},
"singleUse": true
},
},
"ssl": {
"_parent": {
"reading": true
},
"_secureContext": "[Circular Reference]this.ws._sender._socket._tlsOptions.secureContext",
"reading": true
}
},
"_firstFragment": true,
"_compress": false,
"_bufferedBytes": 0,
"_deflating": false,
"_queue": []
},
"_socket": "[Circular Reference]this.ws._sender._socket"
}
}
为了重建调用JSON.parse(),然后遍历属性寻找[Circular Reference]标记。然后把它切下来…eval……它将此设置为根对象。
不要评估任何可能被黑的东西。更好的做法是执行string.split('.'),然后按名称查找属性来设置引用。