Chrome sendrequest error: TypeError: Converting circular structure to JSON

后端 未结 11 992
醉梦人生
醉梦人生 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 04:56

    I have experienced the same error when trying to build the message below with jQuery. The circular reference happens when reviewerName was being mistakenly assigned to msg.detail.reviewerName. JQuery's .val() fixed the issue, see last line.

    var reviewerName = $('reviewerName'); // <input type="text" id="taskName" />;
    var msg = {"type":"A", "detail":{"managerReview":true} };
    msg.detail.reviewerName = reviewerName; // Error
    msg.detail.reviewerName = reviewerName.val(); // Fixed
    
    0 讨论(0)
  • 2020-11-22 04:57

    One approach is to strip object and functions from main object. And stringify the simpler form

    function simpleStringify (object){
        var simpleObject = {};
        for (var prop in object ){
            if (!object.hasOwnProperty(prop)){
                continue;
            }
            if (typeof(object[prop]) == 'object'){
                continue;
            }
            if (typeof(object[prop]) == 'function'){
                continue;
            }
            simpleObject[prop] = object[prop];
        }
        return JSON.stringify(simpleObject); // returns cleaned up JSON
    };
    
    0 讨论(0)
  • 2020-11-22 04:58

    It means that the object you pass in the request (I guess it is pagedoc) has a circular reference, something like:

    var a = {};
    a.b = a;
    

    JSON.stringify cannot convert structures like this.

    N.B.: This would be the case with DOM nodes, which have circular references, even if they are not attached to the DOM tree. Each node has an ownerDocument which refers to document in most cases. document has a reference to the DOM tree at least through document.body and document.body.ownerDocument refers back to document again, which is only one of multiple circular references in the DOM tree.

    0 讨论(0)
  • 2020-11-22 04:58

    This might not be related answer, but this link Detecting and fixing circular references in JavaScript might helpful to detect objects which are causing circular dependency.

    0 讨论(0)
  • 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));

    0 讨论(0)
  • 2020-11-22 05:03

    I resolve this problem on NodeJS like this:

    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));
    
    0 讨论(0)
提交回复
热议问题