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.
🌐
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 - If you open the file user_profile.json, ... can modify the code as follows: const prettyJsonData = JSON.stringify(userProfile, null, 2); fs.writeFileSync('pretty_user_profile.json', prettyJsonData);...
🌐
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.
🌐
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 ...
🌐
HeyNode
heynode.com › tutorial › readwrite-json-files-nodejs
Read/Write JSON Files with Node.js | HeyNode
Say you have a customer.json file saved to disk that holds a record for a customer in your store. As part of your store app, you want to access the customer’s address, and then update the order count after an order is placed. In this tutorial, we are going to look at how to read and write to our customer.json file.
🌐
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 - You can use the fs.writeFile() method to write data to a file. Before writing to a file, ensure that your data is in JSON format. If you have a JavaScript object, convert it to a JSON string using JSON.stringify(). const fs = require('fs'); ...
Find elsewhere
🌐
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:
🌐
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 ?
🌐
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();
🌐
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 - Here's the gist of it. Node.js provides a built-in module called fs that allows you to work with the file system. You can use the fs.writeFileSync() method to write a JSON object to a file.
🌐
Stack Abuse
stackabuse.com › reading-and-writing-json-files-with-node-js
Reading and Writing JSON Files with Node.js
July 8, 2024 - You can also use the global require method to handle reading/parsing JSON data from a file in a single line of code. However, require is synchronous and can only read JSON data from files with .json extension. Similarly, the writeFile and writeFileSync functions from the fs module write JSON data to the file in an asynchronous and synchronous manner respectively.
🌐
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 - You can use the JSON.stringify() method to convert your JSON object into its string representation, and then use the file system fs module to write it to a file.
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.

🌐
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:
🌐
LogRocket
blog.logrocket.com › home › reading and writing json files in node.js: a complete tutorial
Reading and writing JSON files in Node.js: A complete tutorial - LogRocket Blog
November 1, 2024 - Just like reading JSON files, the fs module provides built-in methods for writing to JSON files. You can use the writeFile, as discussed above, and the writeFileSync methods, as discussed below.
🌐
Attacomsian
attacomsian.com › blog › javascript-pretty-print-json
How to pretty-print a JSON object with JavaScript
October 15, 2022 - In this article, you'll learn how to use the JSON.stringify() method to pretty-print a JSON object in JavaScript.