Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
like image 600
Chris Moretti Avatar asked Jan 06 '23 02:01

Chris Moretti


2 Answers

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));
like image 195
Kalman Avatar answered Jan 13 '23 08:01

Kalman


Your users aren't keyed off of name, they're in a numerically indexed array. You have to use delete users.users[1], or better yet, use .splice().

If you want to delete based on username, you're going to have to loop through.

users.users.forEach((user, index) => {
  if (user.username === 'test2') {
    users.users.splice(index, 1);
  }
});

For anything much more complicated, consider a client-side database like TaffyDB.

like image 38
Brad Avatar answered Jan 13 '23 08:01

Brad