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 []
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.