开发者

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:" + sessio开发者_Go百科n);
> Session:[object Object]

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


Try this one:

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

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


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


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


This will work with any object:

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


console.dir() is the most direct way.


console.log(obj);

Run: node app.js > output.txt


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜