The Wayback Machine - https://web.archive.org/web/20240531091914/https://www.geeksforgeeks.org/how-to-add-data-in-json-file-using-node-js/
Open In App

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

Last Updated : 29 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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

  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:

    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);
  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:



Similar Reads

Convert JSON file into CSV file and displaying the data using Node.js
There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js. JSON stands for Jav
3 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more. Approach: We are going to fetch JSON data from one of free website,
2 min read
How to read and write JSON file using Node ?
Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises. JSON(JavaScript Object Notation) is a simple and text-based format for exchanging data between diff
3 min read
How to fetch data from JSON file and display in HTML table using jQuery ?
The task is to fetch data from the given JSON file and convert data into an HTML table. Approach: We have a JSON file containing data in the form of an array of objects. In our code, we are using jQuery to complete our task. The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two
3 min read
How to append data in JSON file through HTML form using PHP ?
The purpose of this article is to append data to a JSON file through HTML form using PHP. Approach 1: If the JSON file is not created then we create a new JSON file, send data to it, and append data in it. To see how to create a JSON file by taking data from the HTML form, refer this link. Approach 2: If the JSON file is already created then we dir
4 min read
How to Update Data in JSON File using JavaScript ?
JSON stands for JavaScript Object Notation. It is a text-based data exchange format that allows you to transfer data between different languages and platforms. JavaScript is commonly used to interact with JSON files. Updating data in a JSON file involves reading the file and then making the necessary changes to the JSON object and then writing the
4 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read
How to work with Node.js and JSON file ?
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. With node.js as backend, the developer can maintain a single codebase for an entire application in javaScript.JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging data.Creating a Script: Node.js scripts are created
4 min read
How to automatically build the package.json file for Node.js projects?
In this article, we will be discussing how to build a package.json file for Node.js Projects. At first, we need to use a code editor for our node.js project. There are various code editors available such as sublime text, Visual Studio, etc. We can use any one of them for our project. What is a package.json file? A package.json file is a JSON file t
3 min read