How to Print Object in Node Js

How to Print Object in Node Js

In the below code (running on Node JS) I am trying to print an object obtained from an external API using JSON.stringify which results in an error:

TypeError: Converting circular structure to JSON

I have looked at the questions on this topic, but none could help. Could some one please suggest:

a) How I could obtain country value from the res object ?

b) How I could print the entire object itself ?

  http.get(' (res) => {     
    console.log(`Got response: ${res.statusCode}`);
    console.log(res.country)  // *** Results in Undefined
    console.log(JSON.stringify(res)); // *** Resulting in a TypeError: Converting circular structure to JSON

    res.resume();
  }).on('error', (e) => {
    console.log(`Got error: ${e.message}`);
  });
3

7 Answers

Basic console.log will not go through long and complex object, and may decide to just print [Object] instead.

A good way to prevent that in node.js is to use util.inspect:

'use strict';
const util = require('util'),
    obj = /*Long and complex object*/;

console.log(util.inspect(obj, {depth: null}));
//depth: null tell util.inspect to open everything until it get to a circular reference, the result can be quite long however.

EDIT: In a pinch (in the REPL for example), a second option is JSON.stringify. No need to require it, but it will break on circular reference instead of printing the fact there is a reference.

2

Print the whole object, it will not have problems with recursive refferences:

console.log(res);

Here's an example for you to see how console.log handles circular refferences:

> var q = {a:0, b:0}
> q.b = q
> console.log(q)
{ a: 0, b: [Circular] }

Also, I would advise to check what data are you actually receiving.

6

By using the http request client, I am able to print the JSON object as well as print the country value. Below is my updated code.

var request = require('request');
request(' function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(response.body);    // Prints the JSON object
    var object = JSON.parse(body);
    console.log(object['country']) // Prints the country value from the JSON object
  }
});

This can print the key of the object and the value of the object in the simplest way. Just try it.

const jsonObj = {
  a: 'somestring',
  b: 42,
  c: false
};

Array.from(Object.keys(jsonObj)).forEach(function(key){
  console.log(key + ":" + jsonObj[key]);
});

In 2021, I just printed using

app.post("/",(req,res) => {
    console.log("HI "+JSON.stringify(req.body));
    res.send("Hi")
});

and got my output as HI {"Hi":"Hi"}.

I sent

{
    "Hi": "Hi"
}

as my post request body.

Only doing console.log(req.body) printed [object Object] on console but now this works.

You do not actually get data in res. You need on('data') and on.('end')

body is a string. It gets append on data received, so on complete you will need to parse data into json

http.get("", function(res) {
    var body = '';
    res.on('data', function(data){
        body = body + data;
    });

    res.on('end', function() {
        var parsed = {};  
        try{
            parsed = JSON.parse(body); // i have checked its working correctly
        }
        catch(er){
            //do nothing it is already json
        }
        console.log(parsed.country);
    });
});

Noe from parsed which is a json object, you can get any property

You can pass two arguments to console.log()

Try this code after installing "yargs" And it will print whole object

console.log('object is' , yargs.argv);

I think may be it will help you to print whole object :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.