Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

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:

{   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 ?

like image 587
Rajat Avatar asked Apr 14 '11 23:04

Rajat


People also ask

Which pipe is used for pretty printing the JSON value?

Angular json pipe is also useful for debugging purpose because it displays all the properties of the object in pretty print json format.


1 Answers

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.stringify() docs at MDN, Node fs docs

like image 50
Ricardo Tomasi Avatar answered Sep 22 '22 08:09

Ricardo Tomasi