1

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 []
unreal123
  • 13
  • 2
  • 2
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+property+on+array%2C+json.stringify+logs+empty+array) of [Array of Array, JSON.stringify() giving empty array instead of entire object](https://stackoverflow.com/q/28500851/4642212). – Sebastian Simon Feb 17 '21 at 20:35

1 Answers1

1

It's an array not an object. If randomJsonObject was an object then this would have worked.

Try the following, set randomJsonObect = {} in the beginning and do your experiment again.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Feras Wilson
  • 380
  • 1
  • 3
  • 13
  • I am kind of smashing my head against the wall right now. How wasn't I able to see this it's so obvious! :D But still kind of weird that it works when not using it without .stringify... Whatever, now it works! Thank you so much! ^^I guess that happens when I change my code so my randomJsonObject isn't an Object anymore... That's probably why it worked before, now everything makes sense – unreal123 Feb 17 '21 at 20:40