0

I have a json file data.json it has 3 fields id, name and address. I want to add a new object in that file using JS at runtime through some function. How can I do that?

2 Answers2

0

Assuming your file has

{
    id: 1,
    name: "Binayak",
    address: "stackoverflow"
}

You can use fs to read & write file

const fs = require('fs');

let data = fs.readFileSync(filePath, "utf-8");
data = JSON.parse(data);
data.myKey = {
    new: "object"
}

fs.writeFileSync(filePath, JSON.stringify(data));

will give

{
    id: 1,
    name: "Binayak",
    address: "stackoverflow",
    myKey: {
        new: "object"
    }
}
0

To achieve this you have to open the file in node, read the parse the json content, modify the js variable and then stringify and save the results.

This might be what you're looking for: const fs = require("fs");

//Reads the file, and executes function on completion
fs.readFile("DIRECTORY_TO_FILE/data.json", "utf-8", (err, result) => {
  if (err) throw err;
  let data = JSON.parse(result);

  //Modify your data object here

  //Saves the file, make sure to provide the right directory
  fs.writeFile(
    "DIRECTORY_TO_FILE/data.json",
    JSON.stringify(data),
    "utf-8",
    function(err) {
      console.log("File saved successfuly!");
    }
  );
});
Ralph Najm
  • 239
  • 1
  • 5