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

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

问:

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




转载于:https://my.oschina.net/uniquejava/blog/227275

你可能感兴趣的:(node格式化输出(漂亮的)json文件)