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?
Asked
Active
Viewed 88 times
0
-
1@libik I tried the same. It didn`t worked out sir. :) – Oct 26 '18 at 11:40
-
I hope you're talking about node since you haven't tagged it in your question – Sajal Preet Singh Oct 26 '18 at 11:41
-
@SajalPreetSingh yes, do you have any reference to the solution? – Oct 26 '18 at 11:43
-
Refer https://www.quora.com/How-do-I-make-a-JSON-file-with-JavaScript – Sumesh TG Oct 26 '18 at 11:47
-
Thanks @SumeshTG – Oct 26 '18 at 11:47
-
Possible duplicate of [write/add data in JSON file using node.js](https://stackoverflow.com/questions/36856232/write-add-data-in-json-file-using-node-js) – Sajal Preet Singh Oct 26 '18 at 11:59
2 Answers
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"
}
}

Sajal Preet Singh
- 369
- 1
- 11
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