2019独角兽企业重金招聘Python工程师标准>>>
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,
}
*/
其它答案(完整示例):
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);
}
});