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


Question

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.

1
161
7/16/2017 10:24:29 AM

Accepted Answer

Try this one:

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

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

260
7/16/2017 10:26:16 AM

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon