我有一个大对象要转换成JSON并发送。然而,它具有圆形结构。我想丢弃任何存在的循环引用,并发送任何可以字符串化的引用。我该怎么做?

谢谢

var obj = {
  a: "foo",
  b: obj
}

我想将对象字符串化为:

{"a":"foo"}

当前回答

要更新重写JSON工作方式的答案(可能不推荐,但非常简单),不要使用循环JSON(已弃用)。相反,使用后续的,扁平的:

https://www.npmjs.com/package/flatted

借用了上面@user1541685的旧答案,但替换为新答案:

npm i—保存展平

然后在js文件中

const CircularJSON = require('flatted');
const json = CircularJSON.stringify(obj);

其他回答

在Node.js中,您可以使用util.inspect(object)。它会自动将循环链接替换为“[circular]”。


尽管是内置的(不需要安装),但必须导入它

import * as util from 'util' // has no default export
import { inspect } from 'util' // or directly
// or 
var util = require('util')

要使用它,只需调用

console.log(util.inspect(myObject))

还要注意,您可以传递options对象以进行检查(请参见上面的链接)

inspect(myObject[, options: {showHidden, depth, colors, showProxy, ...moreOptions}])


请阅读下面的评论并给予表扬。。。

使用带有替换符的JSON.stringify方法。有关详细信息,请阅读本文档。http://msdn.microsoft.com/en-us/library/cc836459%28v=vs.94%29.aspx

var obj = {
  a: "foo",
  b: obj
}

var replacement = {"b":undefined};

alert(JSON.stringify(obj,replacement));

找出用循环引用填充替换数组的方法。您可以使用typeof方法来查找属性的类型是否为“object”(引用),并使用精确的等式检查(==)来验证循环引用。

就这样吧

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是其继任者。

本线程中的大多数答案都是专门针对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));

我想知道为什么还没有人从MDN页面发布正确的解决方案。。。

const circular Reference={otherData:123};circular Reference.imy=circular参考;常量getCircularReplacer=()=>{const seed=new WeakSet();return(键,值)=>{if(typeof value==“object”&&value!==null){if(seed.has(value)){回来}见add(值);}返回值;};};const stringified=JSON.stringify(circularReference,getCircularReplacer());console.log(字符串化);

Seen值应该存储在集合中,而不是数组中(每个元素都会调用replacer)。

与公认的答案一样,此解决方案删除了所有重复值,而不仅仅是循环值。但至少它没有指数级的复杂性。