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

谢谢

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

我想将对象字符串化为:

{"a":"foo"}

当前回答

我知道这是一个老问题,但我想建议一个我创建的NPM包,叫做智能循环,它的工作方式与其他建议的方式不同。如果您使用的是大而深的对象,它特别有用。

一些功能包括:

将循环引用或对象内部简单重复的结构替换为导致其首次出现的路径(而不仅仅是字符串〔circular〕);通过在广度优先搜索中查找循环,该包确保了该路径尽可能小,这在处理非常大和深度的对象时非常重要,因为这些对象的路径可能非常长且难以遵循(JSON.stringify中的自定义替换是DFS);允许个性化替换,方便简化或忽略对象的不重要部分;最后,路径完全以访问引用字段所需的方式编写,这可以帮助您进行调试。

其他回答

@RobW的答案是正确的,但这更有表现力!因为它使用了hashmap/set:

const customStringify = function (v) {
  const cache = new Set();
  return JSON.stringify(v, function (key, value) {
    if (typeof value === 'object' && value !== null) {
      if (cache.has(value)) {
        // Circular reference found
        try {
          // If this value does not reference a parent it can be deduped
         return JSON.parse(JSON.stringify(value));
        }
        catch (err) {
          // discard key if value cannot be deduped
         return;
        }
      }
      // Store value in our set
      cache.add(value);
    }
    return value;
  });
};

就这样吧

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

我知道这是一个老问题,但我想建议一个我创建的NPM包,叫做智能循环,它的工作方式与其他建议的方式不同。如果您使用的是大而深的对象,它特别有用。

一些功能包括:

将循环引用或对象内部简单重复的结构替换为导致其首次出现的路径(而不仅仅是字符串〔circular〕);通过在广度优先搜索中查找循环,该包确保了该路径尽可能小,这在处理非常大和深度的对象时非常重要,因为这些对象的路径可能非常长且难以遵循(JSON.stringify中的自定义替换是DFS);允许个性化替换,方便简化或忽略对象的不重要部分;最后,路径完全以访问引用字段所需的方式编写,这可以帮助您进行调试。

我这样解决这个问题:

var util = require('util');

// Our circular object
var obj = {foo: {bar: null}, a:{a:{a:{a:{a:{a:{a:{hi: 'Yo!'}}}}}}}};
obj.foo.bar = obj;

// Generate almost valid JS object definition code (typeof string)
var str = util.inspect(b, {depth: null});

// Fix code to the valid state (in this example it is not required, but my object was huge and complex, and I needed this for my case)
str = str
    .replace(/<Buffer[ \w\.]+>/ig, '"buffer"')
    .replace(/\[Function]/ig, 'function(){}')
    .replace(/\[Circular]/ig, '"Circular"')
    .replace(/\{ \[Function: ([\w]+)]/ig, '{ $1: function $1 () {},')
    .replace(/\[Function: ([\w]+)]/ig, 'function $1(){}')
    .replace(/(\w+): ([\w :]+GMT\+[\w \(\)]+),/ig, '$1: new Date("$2"),')
    .replace(/(\S+): ,/ig, '$1: null,');

// Create function to eval stringifyed code
var foo = new Function('return ' + str + ';');

// And have fun
console.log(JSON.stringify(foo(), null, 4));

superserial完全序列化JavaScript对象。

https://github.com/denostack/superserial

用法:

const serializer = new Serializer();

const nodes = [{ self: null as any, siblings: [] as any[] }, {
  self: null as any,
  siblings: [] as any[],
}];
nodes[0].self = nodes[0];
nodes[0].siblings = nodes;
nodes[1].self = nodes[1];
nodes[1].siblings = nodes;

const serialized = serializer.serialize(nodes);

console.log(serialized);

输出:

[$1,$2];{"self":$1,"siblings":$0};{"self":$2,"siblings":$0}