Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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('http://ip-api.com/json', (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}`);
  });
like image 611
kurrodu Avatar asked Aug 04 '16 13:08

kurrodu


3 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.

like image 121
DrakaSAN Avatar answered Oct 18 '22 05:10

DrakaSAN


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.

like image 23
Tomáš Zato - Reinstate Monica Avatar answered Oct 18 '22 06:10

Tomáš Zato - Reinstate Monica


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('http://ip-api.com/json', 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
  }
});
like image 3
kurrodu Avatar answered Oct 18 '22 05:10

kurrodu