Untitled
unknown
javascript
3 years ago
644 B
10
Indexable
const fs = require("fs")
const addToJson = (id, name) => {
let new_obj = {id: id, name: name}
fs.readFile('new_json.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); // now it's array of objects
console.log(obj)
obj.push(new_obj); //add new object to the array
json = JSON.stringify(obj, null, 2); // convert it back to json
fs.writeFile('new_json.json', json, 'utf8', function(err) {
if (err) throw err;
console.log('complete');
});
}});
}
addToJson(16, "test")Editor is loading...