如何使用node.js漂亮地打印JSON? [英] How can I pretty-print JSON using node.js?
问题描述
这似乎是一个已解决的问题,但我无法找到解决方案.
This seems like a solved problem but I am unable to find a solution for it.
基本上,我读取JSON文件,更改密钥,然后将新的JSON写回到同一文件.一切正常,但是我松开了JSON格式,所以,而不是:
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:
{
name:'test',
version:'1.0'
}
我知道
{name:'test',version:'1.1'}
Node.js中是否可以将格式良好的JSON写入文件?
Is there a way in Node.js to write well formatted JSON to file ?
推荐答案
JSON.stringify
的第三个参数定义用于漂亮打印的空白插入.它可以是字符串或数字(空格数).节点可以使用fs
写入文件系统.示例:
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:
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,
}
*/
请参见 JSON.stringify()文档在MDN , Node fs docs
这篇关于如何使用node.js漂亮地打印JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!