#json
#nodejs
#script

How to update a value in a json file using nodejs?

Anonymous

AnonymousOct 22, 2023

How to update a value in a json file using nodejs?

To update a value in a JSON file using Node.js, you can follow these steps:

  1. Read the JSON file and parse its contents into a JavaScript object.
  2. Update the desired value in the JavaScript object.
  3. Convert the updated JavaScript object back to a JSON string.
  4. Write the JSON string back to the file.

Here's an example implementation:

Let's say we have a JSON file named data.json with the following content:

{
  "name": "John Doe",
  "age": 30,
  "email": "johndoe@example.com"
}

Our goal is to update the value of the "age" field to 35. Here's the code to achieve that:

const fs = require('fs');

// Step 1: Read the JSON file
fs.readFile('data.json', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }

  try {
    // Step 2: Parse the JSON data into a JavaScript object
    const jsonData = JSON.parse(data);

    // Step 3: Update the desired value
    jsonData.age = 35;

    // Step 4: Convert the updated object to a JSON string
    const updatedData = JSON.stringify(jsonData, null, 2);

    // Write the updated JSON string back to the file
    fs.writeFile('data.json', updatedData, 'utf8', (err) => {
      if (err) {
        console.error('Error writing file:', err);
        return;
      }
      console.log('JSON file has been updated.');
    });
  } catch (err) {
    console.error('Error parsing JSON:', err);
  }
});

After running this code, the data.json file will be updated with the new value for the "age" field:

{
  "name": "John Doe",
  "age": 35,
  "email": "johndoe@example.com"
}

The output in the console will be:

JSON file has been updated.

Now, if you open the data.json file, you will see that the "age" field has been updated to 35.

Happy Coding! ❤️