I recently tried using fs to modify a JSON file in a specific directory. That's working fine, I just use
let randomJsonObject = JSON.parse(fs.readFileSync("./file.json", "utf8")); //Should read [] at first because there's nothing written inside this file except []
The problem rises when I try to modify it. I wanted to check if a specific array (just called "something" here already exists, and if not, it should put some values in it. so I tried using
if(!randomJsonObject["something"]) {
randomJsonObject["something"] = [{"name": "asd", "phone": 0}, {"name": "asd222", "phone":234}];
}
The thing is just, when I log the JSON Object, it works fine, but if I try logging JSON.stringify(randomJsonObject) it just logs [], which is my randonJsonObject in the beginning when there's nothing in it and it just got parsed...
console.log(randomJsonObject); //Logs correct JSON Array, with 2 Objects inside it
console.log(JSON.stringify(randomJsonObject)); //Logs [] and nothing else
Does anyone know why that happens? Obviously, if I try saving it to my file then it just saves [] again... Is it a problem with caching? Something else? Help appreciated :) Also I'm pretty new to working with JSON, especially in JavaScript so maybe it's really easy and I just can't see it ^^
fs.writeFile("./file.json", JSON.stringify(randomJsonObject), (err) => {
if (err) console.error(err)
}); //Only saves []