How To Add Elements In JSON Array Using JavaScript

In this tutorial, you will learn how to add elements in JSON array using JavaScript.

JSON short for JavaScript Object Notation is a text-based representation of structured data. JSON is supported in almost all major programming languages.

It is commonly used for transmitting data in web applications and even storing data in some cases.

A small example of JSON is:

{
    "name": "Anjan",
    "website": "CodeSpeedy"
}

The Start

As always we need a package.json file before we can start running the code so run npm init in the terminal.

You do not need an external module to manipulate the JSON files. JavaScript has an inbuilt module named File System (short for fs) to handle files.

We will now import the module like this:

const fs = require('fs');

In the same directory where the JavaScript file is present create the file named code.json. After creating the file to make the work easier add the following code to it:

{
  "notes": []
}

In the above code, we create a key called notes which is an array.

The Main JavaScript Code

In the upcoming code, we will keep adding elements to the array.

We will be creating an object called addition

const addition = {
    name: 'Anjan',
    description: 'This is an example for CodeSpeedy'
};

We will now read the JSON file created before:

fs.readFile('./code.json', 'utf8', function readFileCallback(err, data) {
});

After reading the file we will add an if..else condition to check for errors:

if (err) {
        console.log(err);
}
else {
}

Inside the else condition, i.e. when there are no errors we will add the following code:

var obj = JSON.parse(data);
obj.notes.push(addition);
var json = JSON.stringify(obj, null, 2);

In the following code, we declare a variable named obj that parses the data from the code.json file. We then “push” the object addition into the notes array.

Next, in the same above code, we stringify i.e. create an object into a JSON string.

Now the main task, writing to the file:

fs.writeFile('./code.json', json, 'utf8', err => {
            if (err) {
                console.log(err);
            } else {
                console.log('Done');
            }
        });

Done! The file has just been written to!

The final output of the file should look like this:

{
  "notes": [
    {
      "name": "Anjan",
      "description": "This is an example for CodeSpeedy"
    }
  ]
}

If you keep running the code, it will keep adding new elements in the array.

Add elements in JSON array in JavaScript

const fs = require("fs");

//The object to be added
const addition = {
  name: "Anjan",
  description: "This is an example for CodeSpeedy",
};
fs.readFile("./code.json", "utf8", function readFileCallback(err, data) {
  if (err) {
    console.log(err);
  } else {
    var obj = JSON.parse(data); //now converting it to an object
    obj.notes.push(addition); //adding the data
    var json = JSON.stringify(obj, null, 2); //converting it back to json
    fs.writeFile("./code.json", json, "utf8", (err) => {
      if (err) {
        console.log(err);
      } else {
        console.log("Done");
      }
    });
  }
});

You can also read,

Manipulating Submit Button using JavaScript

Difference Between json.dump() and json.dumps() in Python

Leave a Reply

Your email address will not be published. Required fields are marked *