Chris Moretti
Chris Moretti

Reputation: 607

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));

Upvotes: 4

Views: 14107

Answers (3)

Moksh Malde
Moksh Malde

Reputation: 11

This is one of the ways to remove the task or data from the todos or database I will support like this more as a student

const loadTask = () => {
  try {
    const dataBuffer = fs.readFileSync(filePath);
    const dataJson = dataBuffer.toString();
    return JSON.parse(dataJson);
  } catch (error) {
    return [];
  }
};

const removeTask = (taskToRemove) => {
  let tasks = loadTask();
  const filteredTasks = tasks.filter((task) => task.task !== taskToRemove);

  if (tasks.length === filteredTasks.length) {
    console.log(`Task "${taskToRemove}" not found.`);
  } else {
    saveTasks(filteredTasks);
    console.log(`Task "${taskToRemove}" removed successfully!`);
  }
};

Upvotes: 1

Kalman
Kalman

Reputation: 8121

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));

Upvotes: 8

Brad
Brad

Reputation: 163742

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.

Upvotes: 2

Related Questions