我有一个大对象要转换成JSON并发送。然而,它具有圆形结构。我想丢弃任何存在的循环引用,并发送任何可以字符串化的引用。我该怎么做?
谢谢
var obj = {
a: "foo",
b: obj
}
我想将对象字符串化为:
{"a":"foo"}
我有一个大对象要转换成JSON并发送。然而,它具有圆形结构。我想丢弃任何存在的循环引用,并发送任何可以字符串化的引用。我该怎么做?
谢谢
var obj = {
a: "foo",
b: obj
}
我想将对象字符串化为:
{"a":"foo"}
当前回答
我真的很喜欢Trindaz的解决方案——更详细,但它有一些缺陷。我也为喜欢它的人修过。
此外,我对缓存对象添加了长度限制。
如果我打印的对象真的很大-我的意思是无限大-我想限制我的算法。
JSON.stringifyOnce = function(obj, replacer, indent){
var printedObjects = [];
var printedObjectKeys = [];
function printOnceReplacer(key, value){
if ( printedObjects.length > 2000){ // browsers will not print more than 20K, I don't see the point to allow 2K.. algorithm will not be fast anyway if we have too many objects
return 'object too long';
}
var printedObjIndex = false;
printedObjects.forEach(function(obj, index){
if(obj===value){
printedObjIndex = index;
}
});
if ( key == ''){ //root element
printedObjects.push(obj);
printedObjectKeys.push("root");
return value;
}
else if(printedObjIndex+"" != "false" && typeof(value)=="object"){
if ( printedObjectKeys[printedObjIndex] == "root"){
return "(pointer to root)";
}else{
return "(see " + ((!!value && !!value.constructor) ? value.constructor.name.toLowerCase() : typeof(value)) + " with key " + printedObjectKeys[printedObjIndex] + ")";
}
}else{
var qualifiedKey = key || "(empty key)";
printedObjects.push(value);
printedObjectKeys.push(qualifiedKey);
if(replacer){
return replacer(key, value);
}else{
return value;
}
}
}
return JSON.stringify(obj, printOnceReplacer, indent);
};
其他回答
本线程中的大多数答案都是专门针对JSON.stringify使用的——它们没有显示如何实际删除原始对象树中的循环引用。(好吧,除了之后再次调用JSON.parse之外——这需要重新分配,并且会产生更高的性能影响)
要从源对象树中删除循环引用,可以使用以下函数:https://stackoverflow.com/a/63952549/2441655
然后,可以使用这些通用的循环引用移除器函数安全地调用循环引用敏感函数(如JSON.stringify):
const objTree = {normalProp: true};
objTree.selfReference = objTree;
RemoveCircularLinks(objTree); // without this line, the JSON.stringify call errors
console.log(JSON.stringify(objTree));
此解决方案修复了用户2451227报告的接受答案问题(当o={};JSON.stringify([o,o],getCircularReplacer()))。
函数newCircularReplacer(){常量seenValues=[]返回循环替换器函数circleReplacer(键,值){if(typeof value=='object'&&value!==null&&object.keys(value).length){常量堆栈大小=参见值长度if(堆栈大小){for(设n=stackSize-1;参见nValues[n][key]!==value;--n)seenValues.pop()//清除过期的引用if(参见nValues.includes(value))返回'[Circular]'}参见值push(value)}返回值}}设o={a:1}o.b=o//循环参考控制台日志(JSON.stringify(o,newCircularReplacer())//{a:1,b:[Circular]}✅)o={}a=[o,o]//非循环参考控制台日志(JSON.stringify(a,newCircularReplacer())//[{},{}]✅)
这里有一个解决方案:
仅删除循环(而不是所有重复的对象引用,到目前为止这里发布的大多数解决方案也是如此),不是不必要的冗长,速度快,不需要任何库依赖关系。
function replaceCycles(obj, replacement = undefined, seen = new WeakSet()) {
if (typeof obj === 'object')
if (seen.has(obj))
return replacement
else {
seen.add(obj)
const newObj = {}
for (const key in obj)
newObj[key] = replaceCycles(obj[key], replacement, seen)
seen.delete(obj)
return newObj
}
else
return obj
}
用法:
const a = {
b: 'v1',
c: {
d: 'v2'
}
}
a.e = a.c
a.c.f = a.c
console.log(JSON.stringify(replaceCycles(a, '[CYCLE]')))
输出:
"{'b':'v1','c':{'d':'v2','f':'[CYCLE]'},'e':{'d':'v2','f':'[CYCLE]'}}"
就这样吧
npm i --save circular-json
然后在js文件中
const CircularJSON = require('circular-json');
...
const json = CircularJSON.stringify(obj);
https://github.com/WebReflection/circular-json
注意:我与这个包裹无关。但我确实用它来做这个。
2020年更新
请注意,CircularJSON仅在维护中,flatted是其继任者。
function myStringify(obj, maxDeepLevel = 2) {
if (obj === null) {
return 'null';
}
if (obj === undefined) {
return 'undefined';
}
if (maxDeepLevel < 0 || typeof obj !== 'object') {
return obj.toString();
}
return Object
.entries(obj)
.map(x => x[0] + ': ' + myStringify(x[1], maxDeepLevel - 1))
.join('\r\n');
}