Javascript - Appending object to JSON File

Viewed 9218

I currently have an object:

var obj = {
        username: "James",
        surname: "Brandon",
        id: "[2]"
}

and I want to append it to "users.json":

[
  {    
    "username": "Andy",
    "surname": "Thompson",
    "id": [0],
  },
  {    
    "username": "Moe",
    "surname": "Brown",
    "id": [1]
  }
]

Do you know how I might be able to do this? Thanks in advance.

2 Answers

This answer is assuming that you are working under Node.js.

As I understand your problem you need to solve a few different programming questions.

  1. read and write a .json file

    const fs = require("fs");
    let usersjson = fs.readFileSync("users.json","utf-8");
    
  2. transform a json string into a javascript array

    let users = JSON.parse(usersjson);
    
  3. append an object to an array

    users.push(obj);
    
  4. transform back the array into a json string

    usersjson = JSON.stringify(users);
    
  5. save the json file

    fs.writeFileSync("users.json",usersjson,"utf-8");
    

If your code is running in the browser and users.json is an output file, I guess you already have access to its content.

Use the push() method.

Also, note the missing commas in your objects.

var obj = {
        username: "James",
        surname: "Brandon",
        id: "[2]"
};

var users = [
  {    
    "username": "Andy",
    "surname": "Thompson",
    "id": [0]
  },
  {    
    "username": "Moe",
    "surname": "Brown",
    "id": [1]
  }
];

users.push(obj);
console.log( JSON.stringify(users) );

Now that you have the updated array of objects you can upload it to the server (check this question) or offer a download to the user (check this other question).

As you have been already told, there is no way to directly update client-side a file in the server. It is also not possible to save it directly into the client filesystem.

Related