node 포맷 출력 (예쁜) json 파일

1291 단어 jsonnode
질문:
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);
    }
});

좋은 웹페이지 즐겨찾기