简体   繁体   English

如何在 Node.js 中记录 JSON 对象的内容?

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

Is it possible to print an objects contents eg methods and attributes in Node.js?是否可以在 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.可能与 PHP 中的 print_r(array) 或 Java 中使用 .toString 的方式类似。

Try this one:试试这个:

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

If the object could be converted into JSON, that will work.如果对象可以转换为 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 MDN 上的 JSON.stringify

为了得到更类似于原始console.log(obj)的输出,我通常使用console.log('Status: ' + util.inspect(obj)) (JSON 略有不同)。

This will work with any object:这适用于任何对象:

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

console.dir() 是最直接的方法。

console.log(obj);

运行:节点 app.js > output.txt

This will for most of the objects for outputting in nodejs console这将适用于在 nodejs 控制台中输出的大多数对象

 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.带有深度参数集的console.dir可以解决问题。 This will print JSON objects to any arbitrary depth.这会将 JSON 对象打印到任意深度。 Depth:null means print every level. Depth:null 表示打印每一层。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM