Sometimes, we want to pretty-print JSON using Node.js.
In this article, we’ll look at how to pretty-print JSON using Node.js.
How to pretty-print JSON using Node.js?
To pretty-print JSON using Node.js, we can call JSON.stringify
with the number of spaces to indent the JSON by.
For instance, we write
const fs = require('fs');
fs.writeFile('test.json', JSON.stringify({
a: 1,
b: 2,
c: 3
}, null, 2));
to call fs.writeFile
with the file path and the stringified JSON.
We stringify the JSON by calling JSON.stringify
with the object to stringify as the first argument and the number of spaces to indent each level by as the 3rd argument.
As a result, the JSON written to test.json should be indented with 2 spaces in each level.
Conclusion
To pretty-print JSON using Node.js, we can call JSON.stringify
with the number of spaces to indent the JSON by.