Append a new object to an array in a JSON file

Viewed 1372

How do I add an additional object to an existing JSON file which is an array of objects?

Here's my JS code:

const fs = require("fs");

let Human = { 
    Name: "John",
    age: 20,

};

Human = JSON.stringify(Human, null, 2)

fs.appendFile('users.json', Human, error);

function error(err) {
    console.log("1");
}

This gives the output:

[
    {
      "Name": "John",
      "age": 20,
    },
    
    {
      "Name": "John",
      "age": 20,
    }
]{
  "Name": "John",
  "age": 20,

}

But I need:

[
    {
      "Name": "John",
      "age": 20,
    },
    
    {
      "Name": "John",
      "age": 20,
    },
    {
      "Name": "John",
      "age": 20,

    }
]

How to make it write to the array correctly?

1 Answers

Appending a pre-serialized element in JSON form to a pre-existing JSON file makes intuitive sense. You might try to slice off the tail "]" in the file, write the new element with a prepended comma, then re-append the "]".

But this can go wrong in so many ways. The better approach is to read the file, parse the JSON into a JS object, make the desired modification(s) to the object, serialize the object back to JSON and finally write the string back to the file.

This code shows all of these steps along with an initial write to generate sample data:

const fs = require("fs").promises;

(async () => {
  // generate a sample JSON file
  const filename = "users.json";
  let users = [
    {
      name: "Amy",
      age: 21,
    },
    {
      name: "Bob",
      age: 23,
    },
  ];
  await fs.writeFile(filename, JSON.stringify(users));

  // append a new user to the JSON file
  const user = {
    name: "John",
    age: 20,
  };
  const file = await fs.readFile(filename);
  users = JSON.parse(file);
  users.push(user);
  await fs.writeFile(filename, JSON.stringify(users, null, 4));
})();
Related