node格式化输出(漂亮的)json文件

2014/04/27 18:23
阅读数 2.1W
问:

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:

{
  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 ?

最佳答案:
JSON.stringifyaccepts a third parameter which defines white-space insertion. It can be a string or a number (number of spaces). Example:

JSON.stringify({ a:1, b:2, c:3 }, null, 4);
/* output:
{
     "a": 1,
     "b": 2,
     "c": 3,
}
*/



See the JSON docs at MDC

其它答案(完整示例):

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




展开阅读全文
打赏
2
8 收藏
分享
加载中
更多评论
打赏
0 评论
8 收藏
2
分享
返回顶部
顶部