如何使用 node.js 漂亮地打印 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5670752/
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
How can I pretty-print JSON using node.js?
提问by Rajat
This seems like a solved problem but I am unable to find a solution for it.
这似乎是一个已解决的问题,但我无法找到解决方案。
Basically, I read a JSON file, change a key, and write back the new JSON to the same file. All works, but I loose the JSON formatting.So, instead of:
基本上,我读取了一个 JSON 文件,更改了一个密钥,然后将新的 JSON 写回到同一个文件中。一切正常,但我失去了 JSON 格式。所以,而不是:
{
name:'test',
version:'1.0'
}
I get
我得到
{name:'test',version:'1.1'}
Is there a way in Node.js to write well formatted JSON to file ?
Node.js 中有没有办法将格式良好的 JSON 写入文件?
回答by Ricardo Tomasi
JSON.stringify's third parameter defines white-space insertion for pretty-printing. It can be a string or a number (number of spaces). Node can write to your filesystem with fs. Example:
JSON.stringify的第三个参数定义了漂亮打印的空白插入。它可以是字符串或数字(空格数)。Node 可以使用fs. 例子:
var fs = require('fs');
fs.writeFile('test.json', JSON.stringify({ a:1, b:2, c:3 }, null, 4));
/* test.json:
{
"a": 1,
"b": 2,
"c": 3,
}
*/
See the JSON.stringify() docs at MDN, Node fs docs
回答by nym
I think this might be useful... I love example code :)
我认为这可能很有用...我喜欢示例代码 :)
var fs = require('fs');
var myData = {
name:'test',
version:'1.0'
}
var outputFilename = '/tmp/my.json';
fs.writeFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("JSON saved to " + outputFilename);
}
});
回答by adius
If you just want to pretty print an object and not export it as valid JSON you can use console.dir().
如果您只想漂亮地打印一个对象而不是将其导出为有效的 JSON,您可以使用console.dir().
It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets.
它使用语法高亮、智能缩进、从键中删除引号并使输出尽可能漂亮。
const jsonString = `{"name":"John","color":"green",
"smoker":false,"id":7,"city":"Berlin"}`
const object = JSON.parse(jsonString)
console.dir(object, {depth: null, colors: true})
Under the hood it is a shortcut for console.log(util.inspect(…)).
The only difference is that it bypasses any custom inspect()function defined on an object.
在引擎盖下,它是console.log(util.inspect(…)). 唯一的区别是它绕过了inspect()在对象上定义的任何自定义函数。
回答by Sanket Berde
If you don't want to store this anywhere, but just view the object for debugging purposes.
如果您不想将其存储在任何地方,而只是出于调试目的查看对象。
console.log(JSON.stringify(object, null, " "));
You can change the third parameter to adjust the indentation.
您可以更改第三个参数来调整缩进。


