如何将循环JSON对象字符串化?

时间:2014-11-17 09:12:52

标签: javascript json

是否有可以对复杂JSON对象进行字符串化的内置方法?

每次我使用JSON.stringfy时都会收到此错误:将循环结构转换为JSON ,我还需要其解析器

这是我的对象的图像 http://imgur.com/s3HbdtQ

4 个答案:

答案 0 :(得分:5)

您无法将循环结构完全转换为JSON:没有什么可以描述那些不能在有限时间内转储的关系。

替代方案:

  • 使用除JSON之外的其他格式(例如Armadan建议的YAML
  • 使用额外的JSON兼容语法扩展JSON以描述引用
  • 使用库删除循环引用(生成一些JSON但没有无法进行字符串化的内容)。我创建了这样一个库:https://github.com/Canop/JSON.prune

答案 1 :(得分:1)

看看这个小图书馆:

https://github.com/WebReflection/circular-json

它将包含循环引用的其他有效JSON对象序列化和反序列化为特殊的JSON格式。

答案 2 :(得分:0)

我推荐Flatted。它很小,效果很好。 压缩后的版本重1KB。

enter image description here

这是他们文档中的一个例子。

var a = [{one: 1}, {two: '2'}];
a[0].a = a;
// a is the main object, will be at index '0'
// {one: 1} is the second object, index '1'
// {two: '2'} the third, in '2', and it has a string
// which will be found at index '3'

Flatted.stringify(a);
// [["1","2"],{"one":1,"a":"0"},{"two":"3"},"2"]

然后可以在必要时将字符串化结果解析回去,并重新构建循环引用。

var a = [{one: 1}, {two: '2'}]
a[0].a = a
Flatted.stringify(a)
var a1 = Flatted.stringify(a)
var a2 = Flatted.parse(a1)

enter image description here

答案 3 :(得分:0)

标准和最佳解决方案是 json-stringify-safe 模块。

这是用法(在模块中描述):

var stringify = require('json-stringify-safe');
var circularObj = {};
circularObj.circularRef = circularObj;
circularObj.list = [ circularObj, circularObj ];
console.log(stringify(circularObj, null, 2));

// Output:

{
  "circularRef": "[Circular]",
  "list": [
    "[Circular]",
    "[Circular]"
  ]
}
相关问题