I have a local JSON file under the path static/json/test.json. Its content is [{"id": 12}, {"id": 44}]. I want to read it, delete the object of the index i from it and rewrite the file so if for example i = 0 the new content should be [{"id": 44}].
What i have tried so far:
let i = 0;
fs.readFile("static/json/test.json", "utf8", function(err, data) {
let obj = JSON.parse(data); // obj is now [{"id": 12}, {"id": 44}]
delete obj[i];
fs.writeFile("static/json/test.json", JSON.stringify(obj), "utf8");
// test.json should now be [{"id": 44}], but its [null, {"id": 44}]
});
If I do this, the content of test.json isn't [{"id": 44}], it's [null, {"id": 44}].
I've read about using obj.splice(i, 1); instead of delete obj[i];, but for some reason that doesnt do anything, without me recieving any errors.
How do I remove the object of index i of this JSON array without leaving null behind?
Edit:
Thanks for the fast answers! Typically obj.splice(i, 1); should work, the cause why it doesn't for me has to have to do with my setup. The working answer for me is
let i = 0;
fs.readFile("static/json/test.json", "utf8", function(err, data) {
let obj = JSON.parse(data); // obj is now [{"id": 12}, {"id": 44}]
delete obj[i];
obj = obj.filter(item => item);
fs.writeFile("static/json/test.json", JSON.stringify(obj), "utf8");
// test.json is now [{"id": 44}]
});
obj.splice(i, 1)instead ofdelete obj[i]works perfectly fine and results intest.jsonto be[{"id":44}]. There must be an other problem with your setup that should be fixed instead of looking for a workaround. What is the console output when you writeobj.splice(i, 1); console.dir(JSON.stringify(obj));instead ofdelete obj[i]