Chrome sendrequest error: TypeError: Converting circular structure to JSON

I've got the following...

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

which calls the following..

case "getBrowserForDocumentAttribute":
  alert("ZOMG HERE");
    reply: getBrowserForDocumentAttribute(request.docu,

However, my code never reaches "ZOMG HERE" but rather throws the following error while running chrome.extension.sendRequest

 Uncaught TypeError: Converting circular structure to JSON

Does anyone have any idea what is causing this?

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.

As per the JSON docs at Mozilla, JSON.Stringify has a second parameter censor which can be used to filter/ignore children items while parsing the tree. However, perhaps you can avoid the circular references.

In Node.js we cannot. So we can do something like this:

function censor(censor) {
  var i = 0;

  return function(key, value) {
    if(i !== 0 && typeof(censor) === 'object' && typeof(value) == 'object' && censor == value) 
      return '[Circular]'; 

    if(i >= 29) // seems to be a harded maximum of 30 serialized objects?
      return '[Unknown]';

    ++i; // so we know we aren't using the original object anymore

    return value;  

var b = {foo: {bar: null}}; = b;

console.log("Censoring: ", b);

console.log("Result: ", JSON.stringify(b, censor(b)));

The result:

Censoring:  { foo: { bar: [Circular] } }
Result: {"foo":{"bar":"[Circular]"}}

Unfortunately there seems to be a maximum of 30 iterations before it automatically assumes it's circular. Otherwise, this should work. I even used areEquivalent from here, but JSON.Stringify still throws the exception after 30 iterations. Still, it's good enough to get a decent representation of the object at a top level, if you really need it. Perhaps somebody can improve upon this though? In Node.js for an HTTP request object, I'm getting:

"limit": null,
"size": 0,
"chunks": [],
"writable": true,
"readable": false,
"_events": {
    "pipe": [null, null],
    "error": [null]
"before": [null],
"after": [],
"response": {
    "output": [],
    "outputEncodings": [],
    "writable": true,
    "_last": false,
    "chunkedEncoding": false,
    "shouldKeepAlive": true,
    "useChunkedEncodingByDefault": true,
    "_hasBody": true,
    "_trailer": "",
    "finished": false,
    "socket": {
        "_handle": {
            "writeQueueSize": 0,
            "socket": "[Unknown]",
            "onread": "[Unknown]"
        "_pendingWriteReqs": "[Unknown]",
        "_flags": "[Unknown]",
        "_connectQueueSize": "[Unknown]",
        "destroyed": "[Unknown]",
        "bytesRead": "[Unknown]",
        "bytesWritten": "[Unknown]",
        "allowHalfOpen": "[Unknown]",
        "writable": "[Unknown]",
        "readable": "[Unknown]",
        "server": "[Unknown]",
        "ondrain": "[Unknown]",
        "_idleTimeout": "[Unknown]",
        "_idleNext": "[Unknown]",
        "_idlePrev": "[Unknown]",
        "_idleStart": "[Unknown]",
        "_events": "[Unknown]",
        "ondata": "[Unknown]",
        "onend": "[Unknown]",
        "_httpMessage": "[Unknown]"
    "connection": "[Unknown]",
    "_events": "[Unknown]",
    "_headers": "[Unknown]",
    "_headerNames": "[Unknown]",
    "_pipeCount": "[Unknown]"
"headers": "[Unknown]",
"target": "[Unknown]",
"_pipeCount": "[Unknown]",
"method": "[Unknown]",
"url": "[Unknown]",
"query": "[Unknown]",
"ended": "[Unknown]"

I created a small Node.js module to do this here: Feel free to improve/contribute!

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)){
        if (typeof(object[prop]) == 'object'){
        if (typeof(object[prop]) == 'function'){
        simpleObject[prop] = object[prop];
    return JSON.stringify(simpleObject); // returns cleaned up JSON

I normally use the circular-json npm package to solve this.

// Felix Kling's example
var a = {};
a.b = a;
// load circular-json module
var CircularJSON = require('circular-json');

Note: circular-json has been deprecated, I now use flatted (from the creator of CircularJSON):

// ESM
import {parse, stringify} from 'flatted/esm';

// CJS
const {parse, stringify} = require('flatted/cjs');

const a = [{}];
a[0].a = a;

stringify(a); // [["1","0"],{"a":"0"}]


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) {
                    cleanObject[key] = copyWithoutCircularReferences(references, value);
                } 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;


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.

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;

// 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));

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

I was getting the same error with jQuery formvaliadator, but when I removed a console.log inside success: function, it worked.

For my case I was getting that error when I was using async function on my server-side to fetch documents using mongoose. It turned out that the reason was I forgot to put await before calling find({}) method. Adding that part fixed my issue.

This works and tells you which properties are circular. It also allows for reconstructing the object with the references

  JSON.stringifyWithCircularRefs = (function() {
    const refs = new Map();
    const parents = [];
    const path = ["this"];

    function clear() {
      parents.length = 0;
      path.length = 1;

    function updateParents(key, value) {
      var idx = parents.length - 1;
      var prev = parents[idx];
      if (prev[key] === value || idx === 0) {
      } else {
        while (idx-- >= 0) {
          prev = parents[idx];
          if (prev[key] === value) {
            idx += 2;
            parents.length = idx;
            path.length = idx;
            parents[idx] = value;
            path[idx] = key;

    function checkCircular(key, value) {
      if (value != null) {
        if (typeof value === "object") {
          if (key) { updateParents(key, value); }

          let other = refs.get(value);
          if (other) {
            return '[Circular Reference]' + other;
          } else {
            refs.set(value, path.join('.'));
      return value;

    return function stringifyWithCircularRefs(obj, space) {
      try {
        return JSON.stringify(obj, checkCircular, space);
      } finally {

Example with a lot of the noise removed:

    "requestStartTime": "2020-05-22...",
    "ws": {
        "_events": {},
        "readyState": 2,
        "_closeTimer": {
            "_idleTimeout": 30000,
            "_idlePrev": {
                "_idleNext": "[Circular Reference]",
                "_idlePrev": "[Circular Reference]",
                "expiry": 33764,
                "id": -9007199254740987,
                "msecs": 30000,
                "priorityQueuePosition": 2
            "_idleNext": "[Circular Reference]",
            "_idleStart": 3764,
            "_destroyed": false
        "_closeCode": 1006,
        "_extensions": {},
        "_receiver": {
            "_binaryType": "nodebuffer",
            "_extensions": "[Circular Reference]",
        "_sender": {
            "_extensions": "[Circular Reference]",
            "_socket": {
                "_tlsOptions": {
                    "pipe": false,
                    "secureContext": {
                        "context": {},
                        "singleUse": true
                "ssl": {
                    "_parent": {
                        "reading": true
                    "_secureContext": "[Circular Reference]",
                    "reading": true
            "_firstFragment": true,
            "_compress": false,
            "_bufferedBytes": 0,
            "_deflating": false,
            "_queue": []
        "_socket": "[Circular Reference]"

To reconstruct call JSON.parse() then loop through the properties looking for the [Circular Reference] tag. Then chop that off and... eval... it with this set to the root object.

Don't eval anything that can be hacked. Better practice would be to do string.split('.') then lookup the properties by name to set the reference.