我有一个大对象,想要转换为JSON并发送。但是它具有圆形结构。我想抛弃任何存在的循环引用,并发送任何可以字符串化的内容。我怎么做?
谢谢。
var obj = {
a: "foo",
b: obj
}
我想将obj分为:
{"a":"foo"}
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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句