Yochran
Yochran

Reputation: 17

How to append to JSON file through JS (NON Arrays)

I'm trying to append to a json file that looks like this:

{
    Members : {
        "809628306336383088" : 12
    }
}

I'm trying to append this value into Members:

"NewMember" : 1

I want it to end up looking like this:

{
   Members : {
      "809628306336383088" : 12, 
      "NewMember" : 1
    }
}

I'm up at 1:00 AM on a thursday and ive been working on this for hours. I'm stumped, any help is appreciated.

Upvotes: 1

Views: 52

Answers (1)

Felix Kling
Felix Kling

Reputation: 816384

  1. Load the file content (e.g. fs.readFile or fs.readFileSync)
  2. Parse the JSON (JSON.parse)
  3. Add the property (data.Member.NewMember = 1;)
  4. Convert the file back to JSON (JSON.stringify)
  5. Write the JSON back to the file (e.g. fs.writeFile or fs.writeFileSync)

Note that what you are showing is not valid JSON. All property keys mus be enclosed in double quotes. You have to fix that first, otherwise you won't be able to parse the file content as JSON.

Upvotes: 1

Related Questions