1

I'm trying to write to a file in nodejs and I've run into an issue that I haven't found any solutions to online.

economy.people[member.id] = 0
fs.writeFile("./economy.json", JSON.stringify(economy, null, 2), (err) => {
  if (err) throw err;
  console.log(economy)
  console.log(JSON.stringify(economy, null, 2))   
  console.log('The file has been saved!');
})

When running this code, the following is returned:

{ government: 1000, banks: [], people: [ '517854168229216256': 0 ] }
{
  "government": 1000,
  "banks": [],
  "people": []
}
The file has been saved!

I'm wondering why JSON.stringify() returns something different than a console.log(), and what I could do to fix this so that they are the same, and return the same value.

1

1 Answer 1

2

It looks like economy.people is an array, not an object. Setting the property '517854168229216256' to 0 does not actually add that item to the array, so JSON.stringify ignores it.

However, arrays in Javascript are a type of object, and you can set any property on an object. console.log will print out these properties, which is why you're seeing the property when logging, but not when stringifying. Changing people to an object instead of an array should give you the expected result.

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

1 Comment

I totally missed this! Thank you for the answer. (I've got a cooldown to mark it as the answer)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.