如何以类似 JSON 的格式打印圆形结构?

新手上路,请多包涵

我有一个大对象要转换为 JSON 并发送。但是它具有圆形结构。我想扔掉任何存在的循环引用并发送任何可以字符串化的东西。我怎么做?

谢谢。

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

我想将 obj 字符串化为:

{"a":"foo"}

原文由 Harry 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 793
2 个回答

JSON.stringify 与自定义替换器一起使用。例如:

 // Demo: Circular reference
 var circ = {};
 circ.circ = circ;

 // Note: cache should not be re-used by repeated calls to JSON.stringify.
 var cache = [];
 JSON.stringify(circ, (key, value) => {
 if (typeof value === 'object' && value !== null) {
 // Duplicate reference found, discard key
 if (cache.includes(value)) return;

 // Store value in our collection
 cache.push(value);
 }
 return value;
 });
 cache = null; // Enable garbage collection

此示例中的替换器并非 100% 正确(取决于您对“重复”的定义)。在以下情况下,将丢弃一个值:

 var a = {b:1}
 var o = {};
 o.one = a;
 o.two = a;
 // one and two point to the same object, but two is discarded:
 JSON.stringify(o, ...);

但概念是:使用自定义替换器,并跟踪解析的对象值。

作为用 es6 编写的实用函数:

 // safely handles circular references
 JSON.safeStringify = (obj, indent = 2) => {
 let cache = [];
 const retVal = JSON.stringify(
 obj,
 (key, value) =>
 typeof value === "object" && value !== null
 ? cache.includes(value)
 ? undefined // Duplicate reference found, discard key
 : cache.push(value) && value // Store value in our collection
 : value,
 indent
 );
 cache = null;
 return retVal;
 };

 // Example:
 console.log('options', JSON.safeStringify(options))

原文由 Rob W 发布,翻译遵循 CC BY-SA 4.0 许可协议

在 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))

另请注意,您可以传递选项对象进行检查 (请参阅上面的链接)

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


请阅读下面的评论并给予荣誉……

原文由 Erel Segal-Halevi 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题