How can I pretty-print JSON using node.js?

前端 未结 6 1046
心在旅途
心在旅途 2020-11-28 00:22

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

6条回答
  •  粉色の甜心
    2020-11-28 00:52

    I think this might be useful... I love example code :)

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

提交回复
热议问题