Search code examples
jsonnode.jsexpressfs

Removing JSON object from JSON file


I am trying to write a function that removes an object from a json file. The json file is formatted with an array of users as such:

{
  "users": [ 
    {
      "username": "test1",
      "answers": [
        "Red",
        "Blue",
        "Yellow",
        "Green"
      ]
    },
    {
      "username": "test2",
      "answers": [
        "1",
        "2",
        "3",
        "4"
      ]
    } 
  ]
}

The code I wrote is not working for some reason. I want to be able to just pass a variable "test2" into the function and then have that particular user removed from the object, including their answers.

var removeUser = user;
var data = fs.readFileSync('results.json');
var json = JSON.parse(data);
var users = json.users;

delete users.users[user];

fs.writeFileSync('results.json', JSON.stringify(json, null, 2));

Solution

  • You can use filter to remove the user you do not want

    var fs = require('fs');
    var removeUser = "test2";
    var data = fs.readFileSync('results.json');
    var json = JSON.parse(data);
    var users = json.users;
    json.users = users.filter((user) => { return user.username !== removeUser });
    fs.writeFileSync('results.json', JSON.stringify(json, null, 2));