Skip to content Skip to sidebar Skip to footer

How To Beautify/prettify A Json/js File In A Node.js Script

I am searching a way to prettify Json files in a node.js script (not CLI). I found a lot of npm beautifier packages, but none that can simply beautify directly a file. There is esb

Solution 1:

You can prettyprint JSON easily by providing parameters to JSON.stringify().

Many people use this kind of call to prettyprint JSON output. It's still valid JSON, it just contains indentation and newlines.

JSON.stringify(myObject, null, 2);

Solution 2:

you can use the tool esformatter.

edit by @jck: here is JS snippet that works using fs:

var esformatter = require('esformatter');
var fs = require('fs');
var filename = "./myFile.json";
var codeStr = fs.readFileSync(filename).toString();
var formattedCode = esformatter.format(codeStr);
fs.writeFile(filename, formattedCode);

Solution 3:

Alternatively, check out prettyjson! It has been great for me!

Post a Comment for "How To Beautify/prettify A Json/js File In A Node.js Script"