You have to be clear on what you mean by "JSON".

Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]. This one happens to be an array. If you want to add a new element to the array, just push it, as in

var arr = [{a: 1}];
arr.push({b: 2});

< [{a: 1}, {b: 2}]

The word JSON may also be used to refer to a string which is encoded in JSON format:

var json = '[{"a": 1}]';

Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse:

var obj = JSON.parse(json);

Now you can manipulate the object any way you want, including push as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify:

var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'

JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify, and use another ajax call to send the data to the server for storage or other manipulation.

You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.

Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?

Answer from user663031 on Stack Overflow
🌐
W3Schools
w3schools.com › js › js_json.asp
JavaScript JSON
JSON objects are written inside curly braces. Just like in JavaScript, objects can contain multiple name/value pairs:
Top answer
1 of 3
26

You have to be clear on what you mean by "JSON".

Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]. This one happens to be an array. If you want to add a new element to the array, just push it, as in

var arr = [{a: 1}];
arr.push({b: 2});

< [{a: 1}, {b: 2}]

The word JSON may also be used to refer to a string which is encoded in JSON format:

var json = '[{"a": 1}]';

Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse:

var obj = JSON.parse(json);

Now you can manipulate the object any way you want, including push as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify:

var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'

JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify, and use another ajax call to send the data to the server for storage or other manipulation.

You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.

Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?

2 of 3
25

JSON can be written into local storage using the JSON.stringify to serialize a JS object. You cannot write to a JSON file using only JS. Only cookies or local storage

    var obj = {"nissan": "sentra", "color": "green"};

localStorage.setItem('myStorage', JSON.stringify(obj));

And to retrieve the object later

var obj = JSON.parse(localStorage.getItem('myStorage'));
🌐
Thomas Step
thomasstep.com › blog › reading-and-writing-json-in-javascript
Reading and Writing JSON in JavaScript
April 5, 2021 - const fs = require('fs'); const path = require('path'); const testObject = { hello: 'world', myArray: [ 'entry1', 'entry2', 'entry3', ], myNestedObject: { nestedHello: 'nestedWorld', }, }; const testJsonString = JSON.stringify(testObject, null, 2); const filePath = path.join(process.cwd(), 'test.json'); try { fs.writeFileSync(filePath, testJsonString); } catch (err) { console.error(err); } Here is the example script in a version that reads synchronously. const fs = require('fs'); const path = require('path'); const filePath = path.join(process.cwd(), 'test.json'); try { const contents = fs.readFileSync(filePath, 'utf8'); const jsonString = JSON.parse(contents); console.log(jsonString); } catch (err) { console.error(err); } Categories: dev | javascript
🌐
OpenReplay
blog.openreplay.com › how-to-read-and-write-json-in-javascript
How to Read and Write JSON in JavaScript
In this article, you will learn everything you need to know to become an expert when it comes to using JSON in JavaScript. Specifically, you will see how to serialize and parse JSON in JavaScript and read and write JSON files in JavaScript with Node.js.
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.

🌐
GitHub
github.com › jbranchaud › til › blob › master › javascript › write-a-javascript-object-to-a-json-file.md
til/javascript/write-a-javascript-object-to-a-json-file.md at master · jbranchaud/til
import fs from 'fs' const writeJsonToFile = (path, data) => { try { fs.writeFileSync(path, JSON.stringify(data, null, 2), 'utf8') console.log('Data successfully saved to disk') } catch (error) { console.log('An error has occurred ', error) } } const data = { name: 'Super Software LLC', orgIds: [1,3,7,11] } writeJsonToFile('my-data.json', data)
Author   jbranchaud
🌐
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 - You can use the writeFile, as discussed above, and the writeFileSync methods, as discussed below. The difference between the two is that: ... Before writing a JSON file, make sure to serialize the JavaScript object to a JSON string using the JSON.s...
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Learn_web_development › Core › Scripting › JSON
Working with JSON - Learn web development | MDN
If you load this JSON in your JavaScript program as a string, you can parse it into a normal object and then access the data inside it using the same dot/bracket notation we looked at in the JavaScript object basics article.
🌐
Educative
educative.io › answers › how-to-add-data-to-a-json-file-in-javascript
How to add data to a JSON file in JavaScript
Line 18: Convert the JavaScript object back into a JSON string. Lines 20–23: Write updated data into the file, data.json, using the writeFileSync() method.
🌐
Linux Hint
linuxhint.com › read-write-and-parse-json-in-javascript
How to Read, Write and Parse JSON in JavaScript
September 11, 2021 - If we want to write something in a JSON file using JavaScript, we will first need to convert that data into a JSON string by using the JSON.stringify method.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › stringify
JSON.stringify() - JavaScript - MDN Web Docs
The JSON.stringify() static method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
🌐
GeeksforGeeks
geeksforgeeks.org › node.js › how-to-read-and-write-json-file-using-node-js
How to read and write JSON file using Node ? - GeeksforGeeks
July 12, 2025 - Example: Create a users.json file in the same directory where index.js file present. Add following data to the users.json file and write the index.js file code: ... [ { "name": "John", "age": 21, "language": ["JavaScript", "PHP", "Python"] }, { "name": "Smith", "age": 25, "language": ["PHP", "Go", "JavaScript"] } ]
🌐
CodeSignal
codesignal.com › learn › courses › hierarchical-and-structured-data-formats-in-ts › lessons › writing-json-files-using-typescript-and-nodejs
Writing JSON Files Using TypeScript and Node.js
Using JSON.stringify with null and 4 for spacing creates human-readable JSON files that are helpful for debugging and inspection. However, for a compact file, omit the spacing: ... In this lesson, you learned how to construct TypeScript objects and write them to a JSON file using Node.js's fs module.
🌐
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 - Learn how to write as well as read a JSON object from a file by using the Node.js file system module.
🌐
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.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-work-with-json-in-javascript
How To Work with JSON in JavaScript | DigitalOcean
August 26, 2021 - To understand how this works, let’s consider the JSON object sammy: var sammy = { "first_name" : "Sammy", "last_name" : "Shark", "online" : true } In order to access any of the values, we’ll be using dot notation that looks like this: ... The variable sammy is first, followed by a dot, followed by the key to be accessed. To create a JavaScript alert that shows us the value associated with the key first_name in a pop-up, we can do so by calling the JavaScript alert() function:
🌐
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.
🌐
Medium
medium.com › @osiolabs › read-write-json-files-with-node-js-92d03cc82824
Read/Write JSON Files with Node.js | by Osio Labs | Medium
December 2, 2019 - 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.
🌐
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.