typeerror: converting circular structure to json

Cause of typeerror: converting circular structure to json

In this blog, we will study how we can solve the typeerror: converting the circular structure to JSON. As an example, we can take the code that is shown below. While running this code one can notice that this code will throw the above-mentioned error on compilation. 

 

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

 

case "getBrowserForDocumentAttribute":
  alert("ZOMG HERE");
  sendResponse({
    reply: getBrowserForDocumentAttribute(request.docu,request.name)
  });
  break;

 

The error appears to be:

 

 

 

Solution

One main thing while solving any error is to understand the meaning behind that particular error. The meaning of this error is that a circular reference is present in the object you pass in the request.  An example of the above concept is shown below:

 

var a = {};

a.b = a;

 

Even if they are not connected to the DOM tree, DOM nodes that have circular references would exhibit this behavior. Each node has an owner document, which often corresponds to the document. Through document.body and document.body, document at least have a reference to the DOM tree. One of several circular references in the DOM tree is where the owner document refers back to the document once again.

One strategy is to remove the primary object’s objects and functions. also stringifying the more basic form. The approach for the same is:

 

function simpleStringify (object){
    // stringify an object, avoiding circular structures
    // https://stackoverflow.com/a/31557814
    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
};

 

 

Also Read: Consider evaluating a polynomial

 

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *