How to add data in JSON file using Node.js ?

29 Dec, 2021
JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article.
First of all, you need to ensure that the JSON file that you are expecting is not going to consume a large memory. For data that is estimated to consume around 500MB, this method won’t be efficient and you should rather consider using a database system.
Node.js has an in-built module named fs, which stands for File System and enables the user to interact with the file system in a modeled way. To use it, type the code below in your server program.const fs = require('fs');The documentation for fs module can be found here.We can start by creating a JSON file, which will contain an id, a name and a city for this example.Note that you can have as many key-value pairs as you want, but we are using three here for a start. {
    "id": 1,
    "name": "John",
    "city": "London"
}Let’s name this JSON file as data.json.Now that we have a JSON file to write to, first we will make a JavaScript object to access the file.For this, we will use fs.readFileSync() which will give us the data in raw format. To get the data in JSON format, we will use JSON.parse().Thus, the code on our server side will look like this:var data = fs.readFileSync('data.json');
var myObject= JSON.parse(data);Now that we have our object ready, let’s suppose we have a key-value pair of data that we want to add :let newData = {
    "country": "England"
}  We need to use our object(i.e. myObject) to add this data.We will do this by using .push() method as follows:Note: To use push() function, data objects in json file must be stored in array. If JSON file is empty or having single object without array, push() will give error.myObject.push(newData);To write this new data to our JSON file, we will use fs.writeFile() which takes the JSON file and data to be added as parameters. Note that we will have to first convert the object back into raw format before writing it. This will be done using JSON.stringify() method.var newData = JSON.stringify(myObject);
fs.writeFile('data.json', newData, err => {
    // error checking
    if(err) throw err;
    
    console.log("New data added");
});   Now our data.json file would look like this:{
    "id": 1,
    "name": "John",
    "city": "London",
    "country": "England"
}
Node.js has an in-built module named fs, which stands for File System and enables the user to interact with the file system in a modeled way. To use it, type the code below in your server program.const fs = require('fs');The documentation for fs module can be found here.
Node.js has an in-built module named fs, which stands for File System and enables the user to interact with the file system in a modeled way. To use it, type the code below in your server program.
const fs = require('fs');
The documentation for fs module can be found here.
We can start by creating a JSON file, which will contain an id, a name and a city for this example.Note that you can have as many key-value pairs as you want, but we are using three here for a start. {
    "id": 1,
    "name": "John",
    "city": "London"
}Let’s name this JSON file as data.json.
We can start by creating a JSON file, which will contain an id, a name and a city for this example.Note that you can have as many key-value pairs as you want, but we are using three here for a start. 
{
    "id": 1,
    "name": "John",
    "city": "London"
}
Let’s name this JSON file as data.json.
Now that we have a JSON file to write to, first we will make a JavaScript object to access the file.For this, we will use fs.readFileSync() which will give us the data in raw format. To get the data in JSON format, we will use JSON.parse().Thus, the code on our server side will look like this:var data = fs.readFileSync('data.json');
var myObject= JSON.parse(data);
Now that we have a JSON file to write to, first we will make a JavaScript object to access the file.For this, we will use fs.readFileSync() which will give us the data in raw format. To get the data in JSON format, we will use JSON.parse().Thus, the code on our server side will look like this:
var data = fs.readFileSync('data.json');
var myObject= JSON.parse(data);
Now that we have our object ready, let’s suppose we have a key-value pair of data that we want to add :let newData = {
    "country": "England"
}  We need to use our object(i.e. myObject) to add this data.We will do this by using .push() method as follows:Note: To use push() function, data objects in json file must be stored in array. If JSON file is empty or having single object without array, push() will give error.myObject.push(newData);
Now that we have our object ready, let’s suppose we have a key-value pair of data that we want to add :
let newData = {
    "country": "England"
}  
We need to use our object(i.e. myObject) to add this data.We will do this by using .push() method as follows:
Note: To use push() function, data objects in json file must be stored in array. If JSON file is empty or having single object without array, push() will give error.
myObject.push(newData);
To write this new data to our JSON file, we will use fs.writeFile() which takes the JSON file and data to be added as parameters. Note that we will have to first convert the object back into raw format before writing it. This will be done using JSON.stringify() method.var newData = JSON.stringify(myObject);
fs.writeFile('data.json', newData, err => {
    // error checking
    if(err) throw err;
    
    console.log("New data added");
});   Now our data.json file would look like this:{
    "id": 1,
    "name": "John",
    "city": "London",
    "country": "England"
}
To write this new data to our JSON file, we will use fs.writeFile() which takes the JSON file and data to be added as parameters. Note that we will have to first convert the object back into raw format before writing it. This will be done using JSON.stringify() method.
var newData = JSON.stringify(myObject);
fs.writeFile('data.json', newData, err => {
    // error checking
    if(err) throw err;
    
    console.log("New data added");
});   
Now our data.json file would look like this:
{
    "id": 1,
    "name": "John",
    "city": "London",
    "country": "England"
}
Example: The index.js code for the above example.
index.js
// Requiring fs moduleconst fs = require("fs");  // Storing the JSON format data in myObjectvar data = fs.readFileSync("data.json");var myObject = JSON.parse(data);  // Defining new data to be addedlet newData = {  country: "England",};  // Adding the new data to our objectmyObject.push(newData);  // Writing to our JSON filevar newData2 = JSON.stringify(myObject);fs.writeFile("data2.json", newData2, (err) => {  // Error checking  if (err) throw err;  console.log("New data added");});
Output:
vivekvikigupta
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React