I have a json prepared file with key-value pairs as arrays. I am writing a program to add new static json (in the same format) to the existing file using "fs" module. I am aware that we cannot just straight-up append json data to json file. Hence, I converted both file and to-be added data to string using JSON.stringify() first. Post this, I tried to use fs.write / fs.appendFile to get the data inserted using JSON.parse() but I end up getting error! Also, I tried to use .push() mehtod but it throws err - "undefined"
let fs = require('fs');
let news = {
"person4": [
{
"first": "Karan",
"last": "Mahajan"
}
],
"person5" : [
{
"first": "Sahil",
"last": "Mahajan"
}
]
};
fs.readFile(__dirname + "/" + "repository.json" , "utf-8", (err,data) => {
let x = JSON.stringify(data);
let y = JSON.stringify(news);
let z = x+y;
fs.appendFile(__dirname + "repository.json" , JSON.parse(z) , "utf-8", (err) => {
console.log("error is " + err);
});
});
File: repository.json
{
"person1": [
{
"first": "Nicole",
"last": "Adelstein"
}],
"person2": [
{
"first": "Pleuni",
"last": "Pennings"
}],
"person3": [
{
"first": "Rori",
"last": "Rohlfs"
}]
}