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

后端 未结 7 1668
南旧
南旧 2020-12-12 09:38

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:

相关标签:
7条回答
  • 2020-12-12 09:58

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

    0 讨论(0)
  • 2020-12-12 10:07

    Try this one:

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

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

    0 讨论(0)
  • 2020-12-12 10:07

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

    0 讨论(0)
  • 2020-12-12 10:13
    console.log(obj);
    

    Run: node app.js > output.txt

    0 讨论(0)
  • 2020-12-12 10:18
    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

    0 讨论(0)
  • 2020-12-12 10:19

    console.dir() is the most direct way.

    0 讨论(0)
提交回复
热议问题