4

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?

3
  • Welcome to SO! Please don't try to bypass the quality filter with spam--it's there for a reason. Parse your JSON file as a JS array, use Array#push for the new entry, then re-stringify the object to JSON and dump back to file. Commented Mar 26, 2021 at 13:37
  • @ggorlen TypeError: Cannot read property 'push' of undefined Commented Mar 26, 2021 at 13:49
  • @ggorlen what i need to put into []? Commented Mar 26, 2021 at 14:34

1 Answer 1

4

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

4 Comments

you showed how to add one user, can I add two users in one rush like {name:a},{name:b} to the array? Only the first user is added.
users.push({name: a}, {name: b});. Or just call .push multiple times.
The first will not do it, but the second one with multiple pushs.
You might be doing something wrong. .push() accepts multiple arguments. a = []; a.push(1, 2, 3); console.log(a); produces [1, 2, 3].

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.