How to Add Data in JSON File using Node.js ?
Last Updated :
08 Jan, 2025
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.
Prerequisites:
Approach
To add data in JSON file using the node js we will be using the fs module in node js. We will first get the data from file using fs.readFileSync and store in an object. Then push the new data and write the data using fs.writeFile method to the given json file.
Steps to Add Data in JSON file using Node
Step 1: Import the fs (file system) module
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');
To know more about fs module visit
here.
Step 2: Create a Sample Data
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.
Step 3: Read and Process the Sample 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);
Step 4: Prepare and Push new 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);
Step 5: Stringify and Write the data to JSON file
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");
});
Step 6: Verify the Updated Data
Now our data.json file would look like this:
{
"id": 1,
"name": "John",
"city": "London",
"country": "England"
}
Example: This example demonstrate the above approach to add data to json file using Nodejs.
Node
// Filename - 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:
Conclusion
In conclusion, using Node.js's fs module, you can efficiently add data to JSON files. By reading, parsing, modifying, and writing back data, you can dynamically update your JSON files. This process ensures your data remains up-to-date and easily accessible, essential for applications requiring persistent data storage and manipulation.
Similar Reads
How to Update Data in JSON File using Node? To update data in JSON file using Node.js, we can use the require module to directly import the JSON file. Updating data in a JSON file involves reading the file and then making the necessary changes to the JSON object and writing the updated data back to the file. Table of ContentUsing require() Me
4 min read
How to Get Data from MongoDB using Node.js? One can create a simple Node.js application that allows us to get data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. Also, we use the EJS for our front end to render the simple HTML form and a table to show the data. Prerequisi
6 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 d
4 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 t
3 min read
How to import data from .CSV file into MySQL table using Node.js ? What is .CSV file? The .CSV (Comma Separated Values) files are plain text files that contains a list of data separated by comma(,). It is a format best used for tabular data, row, and columns, exactly like a spreadsheet, just the difference is that the file is in the form of plain text. The idea of
4 min read
How to Parse JSON using Node.js? JSON stands for JavaScript Object Notation. The text-based data exchange format data exchange format allows you to transfer data between different languages and platforms. JavaScript is commonly used to interact with JSON files. JSON parsing is a common task when working with data from APIs, configu
2 min read
How to Post Data in MongoDB Using NodeJS? In this tutorial, we will go through the process of creating a simple Node.js application that allows us to post data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. And also we use the Ejs for our front end to render the simple
5 min read
How to read and write files in Node JS ? NodeJS provides built-in modules for reading and writing files, allowing developers to interact with the file system asynchronously. These modules, namely fs (File System), offer various methods for performing file operations such as reading from files, writing to files, and manipulating file metada
2 min read
How to Post JSON Data using Curl ? One can send the post data using curl (Client for URLs), a command line tool, and a library for transferring data with URLs. It supports various types of protocols. Most of the use cases of the curl command are posting JSON data to a server endpoint. CURLcURL stands for ( Client for URLs) and is a c
3 min read
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
3 min read