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

Jsonnode.js

Json Problem Overview


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.

Json Solutions


Solution 1 - Json

Try this one:

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

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

Solution 2 - Json

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

Solution 3 - Json

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

Solution 4 - Json

This will work with any object:

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

Solution 5 - Json

console.dir() is the most direct way.

Solution 6 - Json

console.log(obj);

Run: node app.js > output.txt

Solution 7 - Json

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"})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJackView Question on Stackoverflow
Solution 1 - JsonAlexander SulfrianView Answer on Stackoverflow
Solution 2 - JsonccgillettView Answer on Stackoverflow
Solution 3 - JsonlapoView Answer on Stackoverflow
Solution 4 - JsonMarwen TrabelsiView Answer on Stackoverflow
Solution 5 - JsonrainabbaView Answer on Stackoverflow
Solution 6 - JsonRostyslav BornitskyiView Answer on Stackoverflow
Solution 7 - Jsonmanoj kumarView Answer on Stackoverflow