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 updated data back to the file.
Table of Content
- Using require() Method
- Using File System Module
Using require() Method
We are going to use a Direct Approach, In this approach we can directly import the json data file and update like we normally update the JavaScript object. In last to update the changes in a Json file that we have made, we need to use a writeFileSync() function of a File System Module to update the changes.
Syntax:
const fs = require('fs');
// Read the JSON file
const jsonData = require('./data.json');
// Update the data
jsonData.key = 'new value';
// 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
//File path: /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.');
//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
We are going to use a File System Module (“fs”). File System Module provides a different different functions to read and write the data to the file. We can use fs.readFileSync(file_name) or fs.readFile(file_name) function to read the content of the data.json file.
Once the data is read from the file. we will parse it into a JavaScript object using JSON.parse() method. JSON.parse() method will converts the JSON string into a JavaScript object. After parsing the JSON data, we can manipulate the JavaScript object like any other object.
Once the data is updated, we will convert the JavaScript object back to a JSON string using JSON.stringify() method. After that we will use fs.writeFileSync() or fs.writeFile() function to write the updated JSON data back to the file.
Note: fs.readFile(file_name) and fs.writeFile() are asynchronous, so we have to handle it using callback functions, promises or the async/await syntax.
Syntax:
const fs = require('fs');
// Read the JSON file
let rawData = fs.readFileSync('data.json');
let jsonData = JSON.parse(rawData);
// Update the data
jsonData.key = 'new value';
// Write the updated data back to the file
fs.writeFileSync('data.json', JSON.stringify(jsonData));
Before Updating data.json file:
{
"key": "old value"
}
After Updating data.json file:
{
"key": "new value"
}
Example : The below example demonstrate updating data in json file using file system module
//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);
}
});
//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.
Contact Us