Skip to content
Related Articles

Related Articles

How to add data in JSON file using NodeJS ?
  • Last Updated : 19 Feb, 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.

  1. 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 modelled 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.

  2. 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.

  3. 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);
  4. 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:

    myObject.push(newData);
  5. 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 module
const fs = require("fs");
  
// Storing the JSON format data in myObject
var data = fs.readFileSync("data.json");
var myObject = JSON.parse(data);
  
// Defining new data to be added
let newData = {
  country: "England",
};
  
// Adding the new data to our object
myObject.push(newData);
  
// Writing to our JSON file
var newData2 = JSON.stringify(myObject);
fs.writeFile("data2.json", newData2, (err) => {
  // Error checking
  if (err) throw err;
  console.log("New data added");
});

Output:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :