Rajat Rajat - 2 months ago 39
JSON Question

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

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:


I get


Is there a way in Node.js to write well formatted JSON to file ?


JSON.stringify's third parameter defines white-space insertion for pretty-printing. It can be a string or a number (number of spaces). Node can write to your filesystem with fs. Example:

var fs = require('fs');

fs.writeFile('test.json', JSON.stringify({ a:1, b:2, c:3 }, null, 4));
/* test.json:
     "a": 1,
     "b": 2,
     "c": 3,

See the JSON docs at MDC, Node fs docs