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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7428235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:34:38  来源:igfitidea点击:

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

jsonnode.js

提问by Hyman

Is it possible to print an objects contents e.g. 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 。

回答by Alexander Sulfrian

Try this one:

试试这个:

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

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

如果对象可以转换为 JSON,那将起作用。

回答by ccgillett

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

回答by lapo

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

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

回答by Marwen Trabelsi

This will work with any object:

这将适用于任何对象:

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

回答by rainabba

console.dir() is the most direct way.

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

回答by Ростислав Борн?цький

console.log(obj);

Run: node app.js > output.txt

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

回答by manoj kumar

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