How do I add an additional object to an existing JSON file which is an array of objects?
Here's my JS code:
const fs = require("fs");
let Human = {
Name: "John",
age: 20,
};
Human = JSON.stringify(Human, null, 2)
fs.appendFile('users.json', Human, error);
function error(err) {
console.log("1");
}
This gives the output:
[
{
"Name": "John",
"age": 20,
},
{
"Name": "John",
"age": 20,
}
]{
"Name": "John",
"age": 20,
}
But I need:
[
{
"Name": "John",
"age": 20,
},
{
"Name": "John",
"age": 20,
},
{
"Name": "John",
"age": 20,
}
]
How to make it write to the array correctly?
Array#pushfor the new entry, then re-stringify the object to JSON and dump back to file.