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

谢谢

var obj = {
  a: "foo",
  b: 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))

使用带有替换符的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”(引用),并使用精确的等式检查(==)来验证循环引用。


当你不知道所有循环引用的键时,对于未来搜索这个问题解决方案的谷歌用户,你可以使用JSON.stringify函数的包装器来排除循环引用。参见示例脚本https://gist.github.com/4653128.

解决方案本质上归结为在数组中保留对先前打印对象的引用,并在返回值之前在替换函数中检查该引用。它比仅排除循环引用更具限制性,因为它还排除了两次打印对象的可能性,其副作用之一是避免循环引用。

包装示例:

function stringifyOnce(obj, replacer, indent){
    var printedObjects = [];
    var printedObjectKeys = [];

    function printOnceReplacer(key, value){
        var printedObjIndex = false;
        printedObjects.forEach(function(obj, index){
            if(obj===value){
                printedObjIndex = index;
            }
        });

        if(printedObjIndex && typeof(value)=="object"){
            return "(see " + value.constructor.name.toLowerCase() + " with key " + printedObjectKeys[printedObjIndex] + ")";
        }else{
            var qualifiedKey = key || "(empty key)";
            printedObjects.push(value);
            printedObjectKeys.push(qualifiedKey);
            if(replacer){
                return replacer(key, value);
            }else{
                return value;
            }
        }
    }
    return JSON.stringify(obj, printOnceReplacer, indent);
}

我真的很喜欢Trindaz的解决方案——更详细,但它有一些缺陷。我也为喜欢它的人修过。

此外,我对缓存对象添加了长度限制。

如果我打印的对象真的很大-我的意思是无限大-我想限制我的算法。

JSON.stringifyOnce = function(obj, replacer, indent){
    var printedObjects = [];
    var printedObjectKeys = [];

    function printOnceReplacer(key, value){
        if ( printedObjects.length > 2000){ // browsers will not print more than 20K, I don't see the point to allow 2K.. algorithm will not be fast anyway if we have too many objects
        return 'object too long';
        }
        var printedObjIndex = false;
        printedObjects.forEach(function(obj, index){
            if(obj===value){
                printedObjIndex = index;
            }
        });

        if ( key == ''){ //root element
             printedObjects.push(obj);
            printedObjectKeys.push("root");
             return value;
        }

        else if(printedObjIndex+"" != "false" && typeof(value)=="object"){
            if ( printedObjectKeys[printedObjIndex] == "root"){
                return "(pointer to root)";
            }else{
                return "(see " + ((!!value && !!value.constructor) ? value.constructor.name.toLowerCase()  : typeof(value)) + " with key " + printedObjectKeys[printedObjIndex] + ")";
            }
        }else{

            var qualifiedKey = key || "(empty key)";
            printedObjects.push(value);
            printedObjectKeys.push(qualifiedKey);
            if(replacer){
                return replacer(key, value);
            }else{
                return value;
            }
        }
    }
    return JSON.stringify(obj, printOnceReplacer, indent);
};

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


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


If

console.log(JSON.stringify(object));

结果是

TypeError:循环对象值

然后,您可能想要这样打印:

var output = '';
for (property in object) {
  output += property + ': ' + object[property]+'; ';
}
console.log(output);

注意,还有一个由Douglas Crockford实现的JSON.decycle方法。看看他的cycle.js。这允许您对几乎任何标准结构进行字符串化:

var a = [];
a[0] = a;
a[1] = 123;
console.log(JSON.stringify(JSON.decycle(a)));
// result: '[{"$ref":"$"},123]'.

您也可以使用逆循环方法重新创建原始对象。因此,您不必从对象中删除循环来将其字符串化。

然而,这对于DOM节点(在现实生活中,这是周期的典型原因)不起作用。例如,这将抛出:

var a = [document.body];
console.log(JSON.stringify(JSON.decycle(a)));

我做了一个叉来解决这个问题(参见我的cycle.js叉)。这应该很好:

var a = [document.body];
console.log(JSON.stringify(JSON.decycle(a, true)));

注意,在我的fork中,JSON.decycle(变量)的工作方式与原始一样,当变量包含DOM节点/元素时,将抛出异常。

当您使用JSON.decycle(variable,true)时,您接受这样一个事实,即结果是不可逆的(retrocycle不会重新创建DOM节点)。但DOM元素在某种程度上应该是可识别的。例如,如果一个div元素有一个id,那么它将被替换为字符串“div#id of the element”。


我建议从@isaacs中检查json字符串安全性——它在NPM中使用。

顺便说一下,如果你没有使用Node.js,你可以从源代码的相关部分复制并粘贴第4-27行。

要安装:

$ npm install json-stringify-safe --save

要使用:

// Require the thing
var stringify = require('json-stringify-safe');

// Take some nasty circular object
var theBigNasty = {
  a: "foo",
  b: theBigNasty
};

// Then clean it up a little bit
var sanitized = JSON.parse(stringify(theBigNasty));

这产生了:

{
  a: 'foo',
  b: '[Circular]'
}

注意,就像@Rob W提到的普通JSON.stringify函数一样,您也可以通过将“replacer”函数作为第二个参数传递给stringify()来自定义净化行为。如果您发现自己需要一个简单的示例来说明如何做到这一点,我只是在这里编写了一个自定义替换器,它将错误、正则表达式和函数强制转换为人类可读的字符串。


使用此类对象解决此问题的另一种解决方案是使用此库

https://github.com/ericmuyser/stringy

它很简单,你可以在几个简单的步骤中解决这个问题。


var a={b:"b"};
a.a=a;
JSON.stringify(preventCircularJson(a));

评估结果为:

"{"b":"b","a":"CIRCULAR_REFERENCE_REMOVED"}"

具有以下功能:

/**
 * Traverses a javascript object, and deletes all circular values
 * @param source object to remove circular references from
 * @param censoredMessage optional: what to put instead of censored values
 * @param censorTheseItems should be kept null, used in recursion
 * @returns {undefined}
 */
function preventCircularJson(source, censoredMessage, censorTheseItems) {
    //init recursive value if this is the first call
    censorTheseItems = censorTheseItems || [source];
    //default if none is specified
    censoredMessage = censoredMessage || "CIRCULAR_REFERENCE_REMOVED";
    //values that have allready apeared will be placed here:
    var recursiveItems = {};
    //initaite a censored clone to return back
    var ret = {};
    //traverse the object:
    for (var key in source) {
        var value = source[key]
        if (typeof value == "object") {
            //re-examine all complex children again later:
            recursiveItems[key] = value;
        } else {
            //simple values copied as is
            ret[key] = value;
        }
    }
    //create list of values to censor:
    var censorChildItems = [];
    for (var key in recursiveItems) {
        var value = source[key];
        //all complex child objects should not apear again in children:
        censorChildItems.push(value);
    }
    //censor all circular values
    for (var key in recursiveItems) {
        var value = source[key];
        var censored = false;
        censorTheseItems.forEach(function (item) {
            if (item === value) {
                censored = true;
            }
        });
        if (censored) {
            //change circular values to this
            value = censoredMessage;
        } else {
            //recursion:
            value = preventCircularJson(value, censoredMessage, censorChildItems.concat(censorTheseItems));
        }
        ret[key] = value

    }

    return ret;
}

我在github上找到了循环json库,它很好地解决了我的问题。

我发现一些有用的好功能:

支持多平台使用,但到目前为止我只使用node.js测试了它。API是相同的,所以您需要做的就是将其包含并用作JSON替换。它有自己的解析方法,所以您可以将“循环”序列化数据转换回对象。


我知道这是一个老问题,但我想建议一个我创建的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));

根据其他答案,我最终得到以下代码。它可以很好地处理循环引用、带有自定义构造函数的对象。

从要序列化的给定对象,

缓存遍历对象时遇到的所有对象,并为每个对象分配一个唯一的hashID(自动递增的数字也有效)找到循环引用后,将新对象中的字段标记为循环,并将原始对象的hashID存储为属性。

Github链接-DecycledJSON

DJSHelper = {};
DJSHelper.Cache = [];
DJSHelper.currentHashID = 0;
DJSHelper.ReviveCache = [];

// DOES NOT SERIALIZE FUNCTION
function DJSNode(name, object, isRoot){
    this.name = name;
    // [ATTRIBUTES] contains the primitive fields of the Node
    this.attributes = {};

    // [CHILDREN] contains the Object/Typed fields of the Node
    // All [CHILDREN] must be of type [DJSNode]
    this.children = []; //Array of DJSNodes only

    // If [IS-ROOT] is true reset the Cache and currentHashId
    // before encoding
    isRoot = typeof isRoot === 'undefined'? true:isRoot;
    this.isRoot = isRoot;
    if(isRoot){
        DJSHelper.Cache = [];
        DJSHelper.currentHashID = 0;

        // CACHE THE ROOT
        object.hashID = DJSHelper.currentHashID++;
        DJSHelper.Cache.push(object);
    }

    for(var a in object){
        if(object.hasOwnProperty(a)){
            var val = object[a];

            if (typeof val === 'object') {
                // IF OBJECT OR NULL REF.

                /***************************************************************************/
                // DO NOT REMOVE THE [FALSE] AS THAT WOULD RESET THE [DJSHELPER.CACHE]
                // AND THE RESULT WOULD BE STACK OVERFLOW
                /***************************************************************************/
                if(val !== null) {
                    if (DJSHelper.Cache.indexOf(val) === -1) {
                        // VAL NOT IN CACHE
                        // ADD THE VAL TO CACHE FIRST -> BEFORE DOING RECURSION
                        val.hashID = DJSHelper.currentHashID++;
                        //console.log("Assigned", val.hashID, "to", a);
                        DJSHelper.Cache.push(val);

                        if (!(val instanceof Array)) {
                            // VAL NOT AN [ARRAY]
                            try {
                                this.children.push(new DJSNode(a, val, false));
                            } catch (err) {
                                console.log(err.message, a);
                                throw err;
                            }
                        } else {
                            // VAL IS AN [ARRAY]
                            var node = new DJSNode(a, {
                                array: true,
                                hashID: val.hashID // HashID of array
                            }, false);
                            val.forEach(function (elem, index) {
                                node.children.push(new DJSNode("elem", {val: elem}, false));
                            });
                            this.children.push(node);
                        }
                    } else {
                        // VAL IN CACHE
                        // ADD A CYCLIC NODE WITH HASH-ID
                        this.children.push(new DJSNode(a, {
                            cyclic: true,
                            hashID: val.hashID
                        }, false));
                    }
                }else{
                    // PUT NULL AS AN ATTRIBUTE
                    this.attributes[a] = 'null';
                }
            } else if (typeof val !== 'function') {
                // MUST BE A PRIMITIVE
                // ADD IT AS AN ATTRIBUTE
                this.attributes[a] = val;
            }
        }
    }

    if(isRoot){
        DJSHelper.Cache = null;
    }
    this.constructorName = object.constructor.name;
}
DJSNode.Revive = function (xmlNode, isRoot) {
    // Default value of [isRoot] is True
    isRoot = typeof isRoot === 'undefined'?true: isRoot;
    var root;
    if(isRoot){
        DJSHelper.ReviveCache = []; //Garbage Collect
    }
    if(window[xmlNode.constructorName].toString().indexOf('[native code]') > -1 ) {
        // yep, native in the browser
        if(xmlNode.constructorName == 'Object'){
            root = {};
        }else{
            return null;
        }
    }else {
        eval('root = new ' + xmlNode.constructorName + "()");
    }

    //CACHE ROOT INTO REVIVE-CACHE
    DJSHelper.ReviveCache[xmlNode.attributes.hashID] = root;

    for(var k in xmlNode.attributes){
        // PRIMITIVE OR NULL REF FIELDS
        if(xmlNode.attributes.hasOwnProperty(k)) {
            var a = xmlNode.attributes[k];
            if(a == 'null'){
                root[k] = null;
            }else {
                root[k] = a;
            }
        }
    }

    xmlNode.children.forEach(function (value) {
        // Each children is an [DJSNode]
        // [Array]s are stored as [DJSNode] with an positive Array attribute
        // So is value

        if(value.attributes.array){
            // ITS AN [ARRAY]
            root[value.name] = [];
            value.children.forEach(function (elem) {
                root[value.name].push(elem.attributes.val);
            });
            //console.log("Caching", value.attributes.hashID);
            DJSHelper.ReviveCache[value.attributes.hashID] = root[value.name];
        }else if(!value.attributes.cyclic){
            // ITS AN [OBJECT]
            root[value.name] = DJSNode.Revive(value, false);
            //console.log("Caching", value.attributes.hashID);
            DJSHelper.ReviveCache[value.attributes.hashID] = root[value.name];
        }
    });

    // [SEPARATE ITERATION] TO MAKE SURE ALL POSSIBLE
    // [CYCLIC] REFERENCES ARE CACHED PROPERLY
    xmlNode.children.forEach(function (value) {
        // Each children is an [DJSNode]
        // [Array]s are stored as [DJSNode] with an positive Array attribute
        // So is value

        if(value.attributes.cyclic){
            // ITS AND [CYCLIC] REFERENCE
            root[value.name] = DJSHelper.ReviveCache[value.attributes.hashID];
        }
    });

    if(isRoot){
        DJSHelper.ReviveCache = null; //Garbage Collect
    }
    return root;
};

DecycledJSON = {};
DecycledJSON.stringify = function (obj) {
    return JSON.stringify(new DJSNode("root", obj));
};
DecycledJSON.parse = function (json, replacerObject) {
    // use the replacerObject to get the null values
    return DJSNode.Revive(JSON.parse(json));
};
DJS = DecycledJSON;

示例用法1:

var obj = {
    id:201,
    box: {
        owner: null,
        key: 'storm'
    },
    lines:[
        'item1',
        23
    ]
};

console.log(obj); // ORIGINAL

// SERIALIZE AND THEN PARSE
var jsonObj = DJS.stringify(obj);
console.log(DJS.parse(jsonObj));

示例用法2:

// PERSON OBJECT

function Person() {
    this.name = null;
    this.child = null;
    this.dad = null;
    this.mom = null;
}
var Dad = new Person();
Dad.name = 'John';
var Mom = new Person();
Mom.name = 'Sarah';
var Child = new Person();
Child.name = 'Kiddo';

Dad.child = Mom.child = Child;
Child.dad = Dad;
Child.mom = Mom;

console.log(Child); // ORIGINAL

// SERIALIZE AND THEN PARSE
var jsonChild = DJS.stringify(Child);
console.log(DJS.parse(jsonChild));

就这样吧

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


我知道这个问题很老,有很多很好的答案,但我发布这个答案是因为它有新的味道(es5+)

Object.defineProperties(JSON{refStringify:{值:函数(obj){let objMap=new Map();let stringified=JSON.stringify(obj,函数(键、值){//仅适用于对象if(值类型==“对象”){//如果具有值,则返回对它的引用if(objMap.has(value))return objMap.get(value);objMap.set(值,`ref${objMap.size+1}`);}返回值;});返回字符串;}},参考解析:{value:函数(str){let parsed=JSON.parse(str);let objMap=_createObjectMap(已解析);objMap.forEach((value,key)=>_replaceKeyWithObject(value,key));返回解析;}},});//***************************示例设a={b: 32中,c:{获取a(){返回a;},获取c(){返回a.c;}}};let stringified=JSON.refStringify(a);let parsed=JSON.refParse(字符串化,2);console.log(已解析,JSON.refStringify(已解析));//***************************/示例//***************************助手函数_createObjectMap(obj){let objMap=new Map();JSON.stringify(obj,(key,value)=>{if(值类型==“对象”){if(objMap.has(value))return objMap.get(value);objMap.set(值,`ref${objMap.size+1}`);}返回值;});返回objMap;}函数_replaceKeyWithObject(key,obj,replaceWithObject=obj){Object.keys(obj).forEach(k=>{设val=obj[k];if(val==键)return(obj[k]=replaceWithObject);if(typeof val=='object'&&val!=replaceWithObject)_replaceKeyWithObject(key,val,replaceWithObject);});}


@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;
  });
};

试试看:

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

var circular_replacer = (value) => {
    var seen = [];
    if (value != null && typeof value == "object") {
        if (seen.indexOf(value) >= 0) return;
        seen.push(value);
    }
    return value;
};

obj = circular_replacer(obj);

JSON.stringify()的第二个参数还允许您指定一个关键字名称数组,该数组应保存在数据中遇到的每个对象中。这可能不适用于所有用例,但却是一个简单得多的解决方案。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

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

var json = JSON.stringify(obj, ['a']);
console.log(json);
// {"a":"foo"}

注意:奇怪的是,OP中的对象定义在最新的Chrome或Firefox中没有抛出循环引用错误。这个答案中的定义被修改了,所以它确实抛出了一个错误。



我想知道为什么还没有人从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)。

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


虽然这已经得到了充分的回答,但您也可以在字符串化之前使用delete运算符显式删除所讨论的属性。

delete obj.b; 
const jsonObject = JSON.stringify(obj);

删除运算符

这将消除构建或维护复杂逻辑以删除循环引用的需要。


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

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

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

npm i—保存展平

然后在js文件中

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

function myStringify(obj, maxDeepLevel = 2) {
  if (obj === null) {
    return 'null';
  }
  if (obj === undefined) {
    return 'undefined';
  }
  if (maxDeepLevel < 0 || typeof obj !== 'object') {
    return obj.toString();
  }
  return Object
    .entries(obj)
    .map(x => x[0] + ': ' + myStringify(x[1], maxDeepLevel - 1))
    .join('\r\n');
}

您可以尝试JSON解析器库:treedoc。它支持循环引用,并使用引用消除重复对象。

纱线添加树文档

import {TD} from 'treedoc'
TD.stringify(obj);

如果您需要更多定制

import {TD, TDEncodeOption} from 'treedoc'

const opt = new TDEncodeOption();
opt.coderOption.setShowType(true).setShowFunction(true);
opt.jsonOption.setIndentFactor(2);
return TD.stringify(obj, opt);

查看器可以查看生成的JSON文件http://treedoc.org,支持通过JSON节点引用进行导航。

我是这个图书馆的作者


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

我们使用对象扫描进行数据处理,这可能是一个可行的解决方案。这就是它的工作方式(也可以正确修剪数组)

.作为控制台包装{最大高度:100%!重要;顶部:0}<script type=“module”>导入对象扫描自'https://cdn.jsdelivr.net/npm/object-scan@18.1.2/lib/index.min.js';const prune=(data)=>对象扫描(['**']{rtn:'计数',filterFn:({isCircular,父级,属性})=>{if(isCircular){if(Array.isArray(父级)){parent.splice(属性,1);}其他{删除父项[属性];}返回true;}return false;},breakFn:({isCircular})=>isCircular==true})(数据);常量obj={a:'foo',c:[0]};obj.b=对象;obj.c.push(obj);console.log(obj);//=><ref*1>{a:'foo',c:[0,[Circular*1]],b:[Circulal*1]}console.log(prune(obj));//返回循环计数// => 2console.log(obj);//=>{a:'foo',c:[0]}</script>

免责声明:我是物体扫描的作者


循环引用时,此代码将失败:

    JSON.stringify(circularReference);
// TypeError: cyclic object value

使用以下代码:

 const getCircularReplacer = () => {
  const seen = new WeakSet();
  return (key, value) => {
    if (typeof value === "object" && value !== null) {
      if (seen.has(value)) {
        return;
      }
      seen.add(value);
    }
    return value;
  };
};

JSON.stringify(circularReference, getCircularReplacer());

我为LoggingUtilities类创建了以下方法。以下方法获取源和目标对象,并通过给定的maxLevel将源分配给目标。

  static assignObjectByLevel(
    sourceObject: any,
    targetObject: any,
    currentLevel: number = 0,
    maxLevel: number = 3,
    showUndefinedValues = false
  ): any {
    if (currentLevel >= maxLevel) {
      return;
    }

    const objQueue = [];
    for (const key in sourceObject) {
      if (sourceObject.hasOwnProperty(key)) {
        const value = sourceObject[key];
        if (typeof value === "object") {
          objQueue.push({ key, value });
        } else {
          targetObject[key] = value;
        }
      } else {
        if (showUndefinedValues) {
          targetObject[key] = "undefined/null";
        }
      }
    }

    while (objQueue.length > 0) {
      const objVal = objQueue.pop();
      currentLevel++;
      targetObject[objVal.key] = {};
      this.assignObjectByLevel(
        objVal.value,
        targetObject[objVal.key],
        currentLevel,
        maxLevel,
        false
      );
    }
  }

用法示例:

   const logObjParam = {
      level1: "value1",
      level2: {
        value2: "value2",
        level3: {
          value3: "value3",
          level4: {
            value4: " value4",
            level5: {
              value5: " value5",
            },
          },
        },
      },
    };

 let logObj = {};
 this.assignObjectByLevel(logObjParam, logObj);

结果:

{
  "level1": "value1",
  "level2": {
    "value2": "value2",
    "level3": {
      "value3": "value3",
      "level4": {}
    }
  }
}

这里有一个解决方案:

仅删除循环(而不是所有重复的对象引用,到目前为止这里发布的大多数解决方案也是如此),不是不必要的冗长,速度快,不需要任何库依赖关系。

function replaceCycles(obj, replacement = undefined, seen = new WeakSet()) {
  if (typeof obj === 'object')
    if (seen.has(obj))
      return replacement 
    else {
      seen.add(obj)
      const newObj = {}
      for (const key in obj)
        newObj[key] = replaceCycles(obj[key], replacement, seen)
      seen.delete(obj)
      return newObj
    }
  else
    return obj
}

用法:

const a = {
  b: 'v1',
  c: {
    d: 'v2'
  }
}

a.e = a.c
a.c.f = a.c

console.log(JSON.stringify(replaceCycles(a, '[CYCLE]')))

输出:

"{'b':'v1','c':{'d':'v2','f':'[CYCLE]'},'e':{'d':'v2','f':'[CYCLE]'}}"

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}

此解决方案修复了用户2451227报告的接受答案问题(当o={};JSON.stringify([o,o],getCircularReplacer()))。

函数newCircularReplacer(){常量seenValues=[]返回循环替换器函数circleReplacer(键,值){if(typeof value=='object'&&value!==null&&object.keys(value).length){常量堆栈大小=参见值长度if(堆栈大小){for(设n=stackSize-1;参见nValues[n][key]!==value;--n)seenValues.pop()//清除过期的引用if(参见nValues.includes(value))返回'[Circular]'}参见值push(value)}返回值}}设o={a:1}o.b=o//循环参考控制台日志(JSON.stringify(o,newCircularReplacer())//{a:1,b:[Circular]}✅)o={}a=[o,o]//非循环参考控制台日志(JSON.stringify(a,newCircularReplacer())//[{},{}]✅)