Open In App

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.

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

Similar Reads