1

I have a file.json file which contains an array ["number1", "number2"] and I'm trying to add "number3" to that array using javascript. But if I define a variable in js file containing this array and try to edit it, only that variable will be edited, when I'm trying to edit the file itself! It sounds like a simple question, but for some reason I didn't find the answer how to do it. Any help is appreciated!

MegaMix_Craft
  • 2,199
  • 3
  • 10
  • 36
  • Does this answer your question? [How to update a value in a json file and save it through node.js](https://stackoverflow.com/questions/10685998/how-to-update-a-value-in-a-json-file-and-save-it-through-node-js) – pilchard Jul 16 '22 at 21:15
  • also: [How to write to a array in JSON file without replacing the entire file](https://stackoverflow.com/questions/70338830/how-to-write-to-a-array-in-json-file-without-replacing-the-entire-file) – pilchard Jul 16 '22 at 21:16

1 Answers1

3
  1. Get the JSON string from the file.
  2. Turn the JSON string into a javascript object.
  3. Edit the object.
  4. Turn the object back into a JSON string.
  5. Replace the contents of the file with the new JSON string.
dqhendricks
  • 19,030
  • 11
  • 50
  • 83
  • Unless your JSON is too big to fit in the memory. Or not feasible doing so. You may also mention reading the JSON file as a stream. – Eldar Jul 16 '22 at 20:06
  • @Eldar Yes, it would get much trickier if it's a giant file, but they explained they were able to edit it as an object in the post. If the JSON file is that big and needs editing however, there may be a more ideal way to store the data. – dqhendricks Jul 16 '22 at 20:08