Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to truncate a file using Node.js ?
Next article icon

How to Update Data in JSON File using Node?

Last Updated : 24 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Content

  • Using require() Method
  • Using File System Module

Using require() Method

This is a direct approach to update the json data. We will use require() method to import the JSON file and read it as JavaScript object. Then directly update the required values. Update the data back to the file synchronously using the writeFileSync() method.

Syntax

const fs = require('fs');

// Read the JSON file using require
const jsonData = require('./data.json');

// Update the data
jsonData.key = 'new value';

// Synchronously write the updated data back to the JSON file
fs.writeFileSync('./data.json', JSON.stringify(jsonData, null, 2));

console.log('Data updated successfully.');

Before Updating data.json file

{
"key": "old value"
}

After Updating data.json file

{
"key": "new value"
}

Steps to create Node.js Application

Step 1: Create a a folder for your application and move to that folder using below command.

cd foldername

Step 2: Create a NodeJS application using the following command:

npm init

Example : The below example demonstrate updating data in json file using require() method

JavaScript
// Filename: index.js  const fs = require('fs');  // Read the JSON file const jsonDataBefore = require('./data.json');  // Print JSON data before updating console.log('Before updating JSON:'); console.log(JSON.stringify(jsonDataBefore, null, 2));  // Update the data jsonDataBefore[0].programmingLanguage.push("JavaScript"); jsonDataBefore[1].programmingLanguage.push("JavaScript");  // Write the updated data back to the JSON file fs.writeFileSync('./data.json', JSON.stringify(jsonDataBefore, null, 2));  // Print JSON data after updating console.log('\nAfter updating JSON:'); console.log(JSON.stringify(jsonDataBefore));  console.log('\nData updated successfully.'); 
JavaScript
//File path: data.json (note: remove this comment line)  [     { "name": "John", "programmingLanguage": ["Python"] },     { "name": "Alice", "programmingLanguage": ["C++"] } ] 

To run the application use the following command

node index.js 

Output

Before updating JSON:
[
{
"name": "John",
"programmingLanguage": [
"Python"
]
},
{
"name": "Alice",
"programmingLanguage": [
"C++"
]
}
]

After updating JSON:
[
{
"name": "John",
"programmingLanguage": [
"Python",
"JavaScript"
]
},
{
"name": "Alice",
"programmingLanguage": [
"C++",
"JavaScript"
]
}
]

Data updated successfully.

Using File System Module

Updating a JSON file in Node.js using the filesystem module we will

  • Read the JSON file using fs.readFile method.
  • Then parse data to JavaScript object using JSON.parse.
  • Update the values in object.
  • Convert the updated object back to a JSON string using JSON.stringify.
  • Write the updated JSON string back to the file using fs.writeFile.

Syntax

const fs = require('fs');

// Read the JSON file
let rawData = fs.readFile('data.json');
let jsonData = JSON.parse(rawData);

// Update the data
jsonData.key = 'new value';

// Write the updated data back to the file
fs.writeFilec('data.json', JSON.stringify(jsonData));

Before Updating data.json file

{
"key": "old value"
}

After Updating data.json file

{
"key": "new value"
}

Example: Updating data in json file using file system module.

JavaScript
//File path: /index.js  const fs = require('fs');  // Define the file path const filePath = 'data.json';  // Read the JSON file fs.readFile(filePath, 'utf8', (err, data) => {     if (err) {         console.error('Error reading file:', err);         return;     }          try {         // Parse the JSON data         const jsonData = JSON.parse(data);          // Display the original data         console.log('Before updating JSON:');         console.log(jsonData);          // Update the data         jsonData.forEach(item => {             item.programmingLanguage.push('JavaScript');         });          // Display the updated data         console.log('\nAfter updating JSON:');         console.log(jsonData);          // Write the updated data back to the file         fs.writeFile(filePath, JSON.stringify(jsonData), (err) => {             if (err) {                 console.error('Error writing file:', err);                 return;             }             console.log('\nData updated successfully.');         });     } catch (error) {         console.error('Error parsing JSON data:', error);     } }); 
JavaScript
//File path: data.json (note: remove this comment line)  [     { "name": "John", "programmingLanguage": ["Python"] },     { "name": "Alice", "programmingLanguage": ["C++"] } ] 

To run the application use the following command

node index.js 

Output

Before updating JSON:
[
{ name: 'John', programmingLanguage: [ 'Python' ] },
{ name: 'Alice', programmingLanguage: [ 'C++' ] }
]

After updating JSON:
[
{ name: 'John', programmingLanguage: [ 'Python', 'JavaScript' ] },
{ name: 'Alice', programmingLanguage: [ 'C++', 'JavaScript' ] }
]

Data updated successfully.

Next Article
How to truncate a file using Node.js ?
author
jaimin78
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JSON

Similar Reads

  • How to Add Data in JSON File using Node.js ?
    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:NPM NodeApproachTo add data in JSON file using the node js
    4 min read
  • How to update data in sqlite3 using Node.js ?
    In this article, we are going to see how to update data in the sqlite3 database using node.js. So for this, we are going to use the run function which is available in sqlite3. This function will help us to run the queries for updating the data. SQLite is a self-contained, high-reliability, embedded,
    4 min read
  • How to truncate a file using Node.js ?
    In this article, we are going to explore How to truncate the complete file using Node. There are two methods to truncate the file of all its data. We can either use the fs.truncate() method or the fs.writeFile() method to replace all the file content. Method 1: The fs.truncate() method in Node.js ca
    3 min read
  • How to Upload File using formidable module in Node.js ?
    A formidable module is used for parsing form data, especially file uploads. It is easy to use and integrate into your project for handling incoming form data and file uploads. ApproachTo upload file using the formidable module in node we will first install formidable. Then create an HTTP server to a
    2 min read
  • How to Download a File Using Node.js?
    Downloading files from the internet is a common task in many Node.js applications, whether it's fetching images, videos, documents, or any other type of file. In this article, we'll explore various methods for downloading files using Node.js, ranging from built-in modules to external libraries. Usin
    3 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 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 Upload File and JSON Data in Postman?
    Postman is a very famous API development tool used to test APIs. Postman simplifies the process of the API lifecycle to create and test better APIs. Now, while we are working with APIs sometimes we need to send JSON as data or upload a file through API. There may be a scenario where we have to do bo
    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
    3 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences