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

Answer from Ricardo Tomasi on Stack Overflow
🌐
GitHub
gist.github.com › collingo › 6700069
Save pretty printed json to file in node · GitHub
Save pretty printed json to file in node · Raw · writeJsonToFile.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › node › json to file
Node.js - How can I save a JSON object to a file using JavaScript? - 30 seconds of code
February 1, 2024 - const JSONToFile = (obj, filename) => { const blob = new Blob([JSON.stringify(obj, null, 2)], { type: 'application/json', }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = ...
🌐
HeyNode
heynode.com › tutorial › readwrite-json-files-nodejs
Read/Write JSON Files with Node.js | HeyNode
First, to write data to a JSON file, we must create a JSON string of the data with JSON.stringify. This returns a JSON string representation of a JavaScript object, which can be written to a file.
🌐
W3Schools
w3schools.io › file › json-nodejs-examples
NodeJS read,write and pretty print JSON file and object example - w3schools
Another way, parse the json file synchronously using the required in nodejs. ... In Node.js, Import json file using the require keyword and It holds the content of the file as a javascript object.
Top answer
1 of 9
609

If this JSON file won't become too big over time, you should try:

  1. Create a JavaScript object with the table array in it

    var obj = {
       table: []
    };
    
  2. Add some data to it, for example:

    obj.table.push({id: 1, square:2});
    
  3. Convert it from an object to a string with JSON.stringify

    var json = JSON.stringify(obj);
    
  4. Use fs to write the file to disk

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    
  5. If you want to append it, read the JSON file and convert it back to an object

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {
        obj = JSON.parse(data); //now it an object
        obj.table.push({id: 2, square:3}); //add some data
        json = JSON.stringify(obj); //convert it back to json
        fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 
    }});
    

This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.

UPDATE:

Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.

2 of 9
57

Please try the following program. You might be expecting this output.

var fs = require('fs');

var data = {}
data.table = []
for (i=0; i <26 ; i++){
   var obj = {
       id: i,
       square: i * i
   }
   data.table.push(obj)
}
fs.writeFile ("input.json", JSON.stringify(data), function(err) {
    if (err) throw err;
    console.log('complete');
    }
);

Save this program in a javascript file, say, square.js.

Then run the program from command prompt using the command node square.js

What it does is, simply overwriting the existing file with new set of data, every time you execute the command.

Happy Coding.

🌐
Milddev
milddev.com › how-to-save-json-data-to-a-file-in-nodejs
save JSON data to a file in Node.js - MildDev
September 24, 2023 - const prettyJsonData = JSON.stringify(userProfile, null, 2); fs.writeFileSync('pretty_user_profile.json', prettyJsonData);
🌐
Attacomsian
attacomsian.com › blog › nodejs-write-json-object-to-file
How to read and write a JSON object to a file in Node.js
October 1, 2022 - const fs = require('fs') // create ... data is saved.') }) To pretty-print the JSON object to the file, you can pass extra parameters to JSON.stringify():...
Find elsewhere
🌐
Edureka Community
edureka.co › home › community › categories › web development › node-js › how can i pretty-print json using node js
How can I pretty-print JSON using node js | Edureka Community
July 12, 2020 - Basically, I read a JSON file, change a key, and write back the new JSON to the same file. All ... in Node.js to write well formatted JSON to file ?
🌐
Research Hubs
researchhubs.com › post › computing › javascript › pretty-print-json.html
Pretty print JSON in Node.js - Research hubs
When you read a JSON file, change the key or value, and write back to the same file, you will lose the JSON formatting. ... Here is a way to pretty print JSON using JSON.stringify. JSON.stringify accepts a third parameter which defines white-space insertion. It can be a string or a number (number ...
🌐
Medium
medium.com › devcodesights › how-to-read-and-write-json-files-in-node-js-step-by-step-instructions-a42bdb193685
How to Read and Write JSON Files in Node.js: Step-by-Step | devCodeSights
October 20, 2024 - Learn how to efficiently read and write JSON files in Node.js with our step-by-step guide. Master JSON handling for APIs, configuration, and data storage to enhance your Node.js applications.
🌐
Attacomsian
attacomsian.com › blog › nodejs-read-write-json-files
How to read and write JSON files in Node.js
October 1, 2022 - Technically, that's all you need to write JSON to a file. However, the data is saved as a single line of string in the file. To pretty-print the JSON object, change the JSON.stringify() method as follows:
🌐
Stack Abuse
stackabuse.com › reading-and-writing-json-files-with-node-js
Reading and Writing JSON Files with Node.js
July 8, 2024 - Given the extensive use of JSON in software applications, and especially JavaScript-based applications, it is important to know how to read and write JSON data to a file in Node.js.
🌐
TutorialKart
tutorialkart.com › nodejs › node-js-write-json-object-to-file
Node.js Write JSON Object to File - Example
November 29, 2020 - Stringify JSON Object. Use JSON.stringify(jsonObject) to convert JSON Object to JSON String. Write the stringified object to file using fs.writeFile() function of Node FS module. In the following Nodejs script, we have JSON data stored as string ...
🌐
Zachary Betz
zwbetz.com › make-pretty-json-output-in-nodejs
Make Pretty JSON Output in Node.js | Zachary Betz
July 16, 2020 - const fs = require('fs'); const path = require('path'); const process = require('process'); const makePrettyJson = (data) => { const string = JSON.stringify(data, null, 2); return string; }; const writeDataToFile = (data, filePath) => { try { console.log(`Writing file ${filePath}`); fs.writeFileSync(filePath, data); } catch (error) { console.error(`Error when writing file ${filePath}`, error); } }; const main = () => { const todoItem = { id: 1, text: 'Buy milk and eggs', done: false }; // Make it pretty const string = makePrettyJson(todoItem); // Log it console.log(string); // Write it const filePath = path.resolve(process.cwd(), 'output.json'); writeDataToFile(string, filePath); }; main();
🌐
Futurestud.io
futurestud.io › tutorials › node-js-write-a-json-object-to-a-file
Node.js — Write a JSON Object to a File - Future Studio
When working on a new feature or app idea, storing data on the file system can be a good solution. You can skip the database setup and save JSON to a file instead. ... JavaScript comes with the JSON class that lets you serialize an object to JSON with JSON.stringify.
🌐
Jamie Tanna
jvt.me › posts › 2019 › 01 › 11 › pretty-printing-json-node-cli
Pretty Printing JSON using Node.JS on the Command Line · Jamie Tanna | Software Engineer
January 11, 2019 - I've previously written about using Python to pretty print JSON and an alternative using Ruby, but another I've not yet spoke about is using Node.JS. As we saw in Converting X.509 and PKCS#8 .pem file to a JWKS (in Node.JS), we can use JSON.stringify with an argument to denote how to pretty-print the JSON: