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

Jsonnode.js

Json Problem Overview


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 Solutions


Solution 1 - Json

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

Solution 2 - Json

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

Solution 3 - Json

If you just want to pretty print an object and not export it as valid JSON you can use console.dir().

It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets.

const jsonString = `{"name":"John","color":"green",
                     "smoker":false,"id":7,"city":"Berlin"}`
const object = JSON.parse(jsonString)

console.dir(object, {depth: null, colors: true})

Screenshot of logged object

Under the hood it is a shortcut for console.log(util.inspect(…)). The only difference is that it bypasses any custom inspect() function defined on an object.

Solution 4 - Json

If you don't want to store this anywhere, but just view the object for debugging purposes.

console.log(JSON.stringify(object, null, "  "));

You can change the third parameter to adjust the indentation.

Solution 5 - Json

what about this?

console.table(object)

sample

Solution 6 - Json

I know this is old question. But maybe this can help you 

JSON string

var jsonStr = '{ "bool": true, "number": 123, "string": "foo bar" }';

Pretty Print JSON

JSON.stringify(JSON.parse(jsonStr), null, 2);

Minify JSON

JSON.stringify(JSON.parse(jsonStr));

Solution 7 - Json

Another workaround would be to make use of prettier to format the JSON. The example below is using 'json' parser but it could also use 'json5', see list of valid parsers.

const prettier = require("prettier");
console.log(prettier.format(JSON.stringify(object),{ semi: false, parser: "json" }));

Solution 8 - Json

if prettify is name value pairs on new lines then specifying number of spaces in stringify didn't work for me the only thing that worked for me was

await fs.promises.writeFile('testdataattr.json',JSON.stringify(datatofile, null,'\r\n'),'utf8') ;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRajatView Question on Stackoverflow
Solution 1 - JsonRicardo TomasiView Answer on Stackoverflow
Solution 2 - JsonnymView Answer on Stackoverflow
Solution 3 - JsonadiusView Answer on Stackoverflow
Solution 4 - JsonSanket BerdeView Answer on Stackoverflow
Solution 5 - JsonPanuwat KulcharatyothinView Answer on Stackoverflow
Solution 6 - JsonillvartView Answer on Stackoverflow
Solution 7 - JsonjkonstView Answer on Stackoverflow
Solution 8 - JsonGMCView Answer on Stackoverflow