Jack
Jack

Reputation: 15872

How do you log content of a JSON object in Node.js?

Is it possible to print an objects contents e.g. methods and attributes in Node.js?

At the moment I'm trying to print the session object and get the following:

console.log("Session:" + session);
> Session:[object Object]

Maybe in a similar way to print_r(array) in PHP, or using .toString in Java.

Upvotes: 201

Views: 186996

Answers (9)

7wp
7wp

Reputation: 12694

If you are still looking for some options, there is a NPM package that might help you, a drop-in replacement for console.log called console-log-json. The nice thing about it is that it will create consistent JSON formatted logs, despite the fact that you can throw at console.log() any number of parameters in any order, including other JSON objects as well as Error objects and plain strings.

It also handles automatically adding some extra helpful attributes such as time stamps and file where the console.log() was called from, etc..

example JSON output

These all get printed to STDOUT so any log shipping and aggregator can pick it up and parse the JSON.

Upvotes: 0

john k
john k

Reputation: 6614

console.dir with the depth argument set will do the trick. This will print JSON objects to any arbitrary depth. Depth:null means print every level.

console.dir(someObject, { depth: null })

Upvotes: 2

manoj kumar
manoj kumar

Reputation: 1

This will for most of the objects for outputting in nodejs console

var util = require('util')
function print (data){
  console.log(util.inspect(data,true,12,true))
  
}

print({name : "Your name" ,age : "Your age"})

Upvotes: 0

Rostyslav Bornitskyi
Rostyslav Bornitskyi

Reputation: 321

console.log(obj);

Run: node app.js > output.txt

Upvotes: 0

Alexander Sulfrian
Alexander Sulfrian

Reputation: 3563

Try this one:

console.log("Session: %j", session);

If the object could be converted into JSON, that will work.

Upvotes: 306

Marwen Trabelsi
Marwen Trabelsi

Reputation: 4257

This will work with any object:

    var util = require("util");
    console.log(util.inspect(myObject, {showHidden: false, depth: null}));

Upvotes: 30

ccgillett
ccgillett

Reputation: 4561

function prettyJSON(obj) {
    console.log(JSON.stringify(obj, null, 2));
}

// obj -> value to convert to a JSON string
// null -> (do nothing)
// 2 -> 2 spaces per indent level

JSON.stringify on MDN

Upvotes: 154

rainabba
rainabba

Reputation: 4277

console.dir() is the most direct way.

Upvotes: 7

lapo
lapo

Reputation: 3224

To have an output more similar to the raw console.log(obj) I usually do use console.log('Status: ' + util.inspect(obj)) (JSON is slightly different).

Upvotes: 33

Related Questions