Chrome sendrequest error: TypeError: Converting circular structure to JSON

后端 未结 11 991
醉梦人生
醉梦人生 2020-11-22 04:16

I\'ve got the following...

chrome.extension.sendRequest({
  req: \"getDocument\",
  docu: pagedoc,
  name: \'name\'
}, function(response){
  var efjs = respo         


        
11条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 05:00

    Based on zainengineer's answer... Another approach is to make a deep copy of the object and strip circular references and stringify the result.

    function cleanStringify(object) {
        if (object && typeof object === 'object') {
            object = copyWithoutCircularReferences([object], object);
        }
        return JSON.stringify(object);
    
        function copyWithoutCircularReferences(references, object) {
            var cleanObject = {};
            Object.keys(object).forEach(function(key) {
                var value = object[key];
                if (value && typeof value === 'object') {
                    if (references.indexOf(value) < 0) {
                        references.push(value);
                        cleanObject[key] = copyWithoutCircularReferences(references, value);
                        references.pop();
                    } else {
                        cleanObject[key] = '###_Circular_###';
                    }
                } else if (typeof value !== 'function') {
                    cleanObject[key] = value;
                }
            });
            return cleanObject;
        }
    }
    
    // Example
    
    var a = {
        name: "a"
    };
    
    var b = {
        name: "b"
    };
    
    b.a = a;
    a.b = b;
    
    console.log(cleanStringify(a));
    console.log(cleanStringify(b));

提交回复
热议问题