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!

2

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

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 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.

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.