AnonymousOct 22, 2023
To add a new key-value pair to an existing JSON file using Node.js, you can follow these steps:
Here's an example of how you can add a new key-value pair to an existing JSON file named data.json
:
data.json
(before modification):
{
"name": "John Doe",
"age": 30
}
Node.js code:
const fs = require('fs');
// Step 1: Read the JSON file
fs.readFile('data.json', 'utf8', (err, data) => {
if (err) {
console.error('Error reading JSON file:', err);
return;
}
try {
// Step 2: Parse the JSON data
const json = JSON.parse(data);
// Step 3: Add a new key-value pair
json.newKey = 'New Value';
// Step 4: Write the updated object back to the JSON file
fs.writeFile('data.json', JSON.stringify(json, null, 2), 'utf8', (err) => {
if (err) {
console.error('Error writing JSON file:', err);
return;
}
console.log('Key-value pair added successfully!');
});
} catch (err) {
console.error('Error parsing JSON:', err);
}
});
After running the code, the data.json
file will be modified with the new key-value pair:
data.json
(after modification):
{
"name": "John Doe",
"age": 30,
"newKey": "New Value"
}
Make sure to have the data.json
file present in the same directory as the script, and replace data.json
with the appropriate file path if it's located elsewhere.