93

I am using request package for node.js

Code :

 var formData = ({first_name:firstname,last_name:lastname,user_name:username, email:email,password:password});

  request.post({url:'http://localhost:8081/register', JSON: formData}, function(err, connection, body) {

exports.Register = function(req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    console.log("Request data " +JSON.stringify(req));

Here I am getting this error :

TypeError: Converting circular structure to JSON

Can anybody tell me what is the problem

Debug Diva
  • 26,058
  • 13
  • 70
  • 123
Hitu Bansal
  • 2,917
  • 10
  • 52
  • 87
  • 1
    Check your data structure. http://stackoverflow.com/questions/4816099/chrome-sendrequest-error-typeerror-converting-circular-structure-to-json – GillesC Nov 24 '14 at 09:14
  • 1
    I am not able to get from here. can u pls tell me what changes i need to made in above code – Hitu Bansal Nov 24 '14 at 09:18
  • 4
    Does this answer your question? [How can I print a circular structure in a JSON-like format?](https://stackoverflow.com/questions/11616630/how-can-i-print-a-circular-structure-in-a-json-like-format) – KyleMit Jul 14 '20 at 20:02

18 Answers18

97

JSON doesn't accept circular objects - objects which reference themselves. JSON.stringify() will throw an error if it comes across one of these.

The request (req) object is circular by nature - Node does that.

In this case, because you just need to log it to the console, you can use the console's native stringifying and avoid using JSON:

console.log("Request data:");
console.log(req);
Scimonster
  • 32,893
  • 9
  • 77
  • 89
  • 1
    I want to extract a token present in req object, so is there a way to extract this or convert the req object to json without using the external library mentioned in the below answer. – Rahul Feb 06 '20 at 08:58
  • 4
    @Rahulroy you should be able to just access the property you need from the req object – Scimonster Feb 06 '20 at 09:46
  • well i this is the req object that i have https://pastebin.com/i1yyaUaB and i am trying to access access_token field in session.keycloak-token. How can i access that. Thanks for the help. – Rahul Feb 06 '20 at 09:55
  • You'll need to JSON.parse() it – Scimonster Feb 06 '20 at 10:33
  • tried that, but that also comes up with new problem of its own. given data loss. – Rahul Feb 06 '20 at 11:13
  • I recommend you ask a new question about your issue – Scimonster Feb 06 '20 at 11:35
  • Thanks, saved my time. Just forgot await while using Mongoose in Node.js – Lema Apr 27 '22 at 13:56
97

I also ran into this issue. It was because I forgot to await for a promise.

Satya
  • 1,569
  • 8
  • 13
13

Try using this npm package. This helped me decoding the res structure from my node while using passport-azure-ad for integrating login using Microsoft account

https://www.npmjs.com/package/circular-json

You can stringify your circular structure by doing:

const str = CircularJSON.stringify(obj);

then you can convert it onto JSON using JSON parser

JSON.parse(str)
Dinesh Nadimpalli
  • 1,441
  • 1
  • 13
  • 23
13

I was able to get the values using this method, found at careerkarma.com

Output looks like this. Preview of the output

I just run this code in the debugger console. Pass your object to this function.
Copy paste the function also.

 const replacerFunc = () => {
    const visited = new WeakSet();
    return (key, value) => {
      if (typeof value === "object" && value !== null) {
        if (visited.has(value)) {
          return;
        }
        visited.add(value);
      }
      return value;
    };
  };
  
  JSON.stringify(circObj, replacerFunc());
Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87
6

use this https://www.npmjs.com/package/json-stringify-safe

var stringify = require('json-stringify-safe');
var circularObj = {};
circularObj.circularRef = circularObj;
circularObj.list = [ circularObj, circularObj ];
console.log(stringify(circularObj, null, 2));


stringify(obj, serializer, indent, decycler)
Mohit Gupta
  • 203
  • 2
  • 12
6

I forgotten to use await keyword in async function. with the given systax

blogRouter.put('/:id', async (request, response) => {
  const updatedBlog = Blog.findByIdAndUpdate(
    request.params.id,
    request.body,
    { new: true }
  );
  response.status(201).json(updatedBlog);
});

Blog.findByIdAndUpdate should be used with the await keyword.

Saurav gupta
  • 387
  • 3
  • 9
4

It's because you don't an async response For example:

app.get(`${api}/users`, async (req, res) => {
    const users = await User.find()
    res.send(users);
   })
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
4

If you are sending reponse , Just use await before response

await res.json({data: req.data});
Nishith Savla
  • 310
  • 2
  • 10
Neeraj Kumar
  • 386
  • 2
  • 9
4

This is because JavaScript structures that include circular references can't be serialized with a"plain" JSON.stringify.

https://www.npmjs.com/package/circular-json mentioned by @Dinesh is a good solution. But this npm package has been deprecated.

So use https://www.npmjs.com/package/flatted npm package directly from the creator of CircularJSON.

Simple usage. In your case, code as follows

import package

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

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

and

console.log("Request data " + stringify(req));
Pankaj Shinde
  • 3,361
  • 2
  • 35
  • 44
3

I was also getting the same error, in my case it was just because of not using await with Users.findById() which returns promise, so response.status().send()/response.send() was getting called before promise is settled (fulfilled or rejected)

Code Snippet

app.get(`${ROUTES.USERS}/:id`, async (request, response) => {
    const _id = request.params.id;
    try {
        // was getting error when not used await
        const user = await User.findById(_id);
        if (!user) {
            response.status(HTTP_STATUS_CODES.NOT_FOUND).send('no user found');
        } else {
            response.send(user);
        }
    } catch (e) {
        response
            .status(HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR)
            .send('Something went wrong, try again after some time.');
    }
});
Ryan M
  • 18,333
  • 31
  • 67
  • 74
Wasit Shafi
  • 854
  • 1
  • 9
  • 15
2

Came across this issue in my Node Api call when I missed to use await keyword in a async method in front of call returning Promise. I solved it by adding await keyword.

Jatin Patel
  • 43
  • 1
  • 4
0

I came across this issue when not using async/await on a asynchronous function (api call). Hence adding them / using the promise handlers properly cleared the error.

Sasi Kumar M
  • 2,440
  • 1
  • 23
  • 23
0

This error message "TypeError: Converting circular structure to JSON" typically occurs when you try to stringify an object that contains circular references using JSON.stringify().

A circular reference occurs when an object references itself in some way. For example, consider the following code:

const obj = { foo: {} };
obj.foo.obj = obj;

In this example, obj contains a circular reference because the foo property of obj contains a reference to obj itself.

When you try to stringify an object like this using JSON.stringify(), it will fail with the error message "TypeError: Converting circular structure to JSON".

To solve this issue, you can use a third-party library like flatted or circular-json, which are specifically designed to handle circular references in JavaScript objects. Here's an example using flatted:

const flatted = require('flatted');

const obj = { foo: {} };
obj.foo.obj = obj;

const str = flatted.stringify(obj);
console.log(str);

In this example, we use flatted.stringify() instead of JSON.stringify(), and it successfully converts the object to a string without throwing an error.

Alternatively, you can modify your object to remove the circular reference before trying to stringify it. For example:

const obj = { foo: {} };
obj.foo.bar = 'baz';

// add circular reference
obj.foo.obj = obj;

// remove circular reference
obj.foo.obj = undefined;

const str = JSON.stringify(obj);
console.log(str);

In this example, we add the circular reference and then remove it before trying to stringify the object. This approach works well if you don't need to preserve the circular reference in the stringified object.

-1

enter image description here

If an object has a different type of property like mentioned in the above image, JSON.stringify() will through an error.

  • This question is asked more than 8 years ago and it has an accepted answer. Please add some details about the reason you are adding a new answer – MD Zand Nov 29 '22 at 20:26
-2

Edit May 22, 2023

I think it is an error which need to be fixed not a feature which is needed. I have faced this issue and tried following things. Hope it helps.

  1. The reference does not have resolved value till the time, we are going to use it. In this case, I have awaited the response, by adding await keyword and checking whether I am returning proper value from the function.

  2. In the second case when I faced this issue I had a json like,

    { obj1: "sample1", obj2: "sample2", obj3: obj3 }

or,

{
 obj1: "sample1",
 obj2: obj1
}

in this case, the value of any of the key in object is again depended on some other key, which was growing the json object recursively. Here, I fixed this dependency of one key on another to resolve it.

  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/31627819) – Ethan Apr 30 '22 at 00:13
-2

For mongodb

so if you are getting errors while fetching data from MongoDB then the problem is async

previously enter image description here

app.get('/users',(req,res,next)=>{
 
 const user=chatUser.find({});
 
 if(!user){
 
 res.status(404).send({message:"there are no users"});
 
 
 }
 
 if(user){
 
 res.json(user);
 
 }
})

After

app.get('/users',async(req,res,next)=>{
 
 const user=await chatUser.find({});
 
 if(!user){
 
 res.status(404).send({message:"there are no users"});
 
 
 }
 
 if(user){
 
 res.json(user);
 
 }
 
})
Kumawat Lalit
  • 410
  • 4
  • 8
-4

Try this as well

console.log(JSON.parse(JSON.stringify(req.body)));
I_love_vegetables
  • 1,575
  • 5
  • 12
  • 26
-7

TypeError: Converting circular structure to JSON in nodejs: This error can be seen on Arangodb when using it with Node.js, because storage is missing in your database. If the archive is created under your database, check in the Aurangobi web interface.

Bhavik Hirani
  • 1,996
  • 4
  • 28
  • 46
Ravi Jain
  • 11
  • 1