0

I got caught on how to delete an element from my json file in node.

Im displaying all my elements from my json file that i have made like this

var json = require('./test.json');

  app.get('/courses', function(req, res) {
    res.render('courses', {
        title: "Hello",
        name: "Fredrik",
        js: json
    });
});

This below is my test.json file

[
{
"id":1,"courseId":"DT162G","courseName":"Javascript-baserad webbutveckling","coursePeriod":1
},
{
"id":2,"courseId":"IK060G","courseName":"Projektledning","coursePeriod":1
},
{
"id":3,"courseId":"DT071G","courseName":"Programmering i C#.NET","coursePeriod":2
}
]

And now i want to be able to delete singel elements that i have looped through in my view

I made this so far but im stuck. And how should the path be in my view?

 <td><a href="/courses/:id">Delete</a></td>

app.delete('/courses/:id', function(req, res) {
  if(json.length <= req.params.id) {
    res.statusCode = 404;
    return res.send('Error 404: No quote found');
  }

  json.splice(req.params.id, 1);

});

3 Answers 3

3

I hope this helps

var fs = require('fs');

app.delete('/courses/:id', function(req, res) {
var indexOfCouseInJson = json.map(function(item) { return item.id; }).indexOf(req.params.id); //find the index of :id
  if(indexOfCouseInJson === -1) {
    res.statusCode = 404;
    return res.send('Error 404: No quote found');
  }

  var result = json.splice(indexOfCouseInJson,1);
  fs.writeFile(jsonFilePath, JSON.stringify(result), function(err){
   if(err) throw err;
   res.json(true);
 });

});
Sign up to request clarification or add additional context in comments.

Comments

0

Why having a json FILE with dynamic data inside? You should use a database (mongodb uses json for example) or you have to store it in another way.

But if you still want to save the data in your file, what you did is correct but after you removed the element you wanted you have to save the file again, I guess.

2 Comments

Hi Im doing a exercise for school and this is the start of the course. So now we are just supposed to work with a json file and the next course it is with Mongo.
Ah ok, then you have to save the file again after that, if you want to read it again.
0

To add on ram's answer, You can use the method readJsonSync as var YourFile = Fs.readJsonSync('file.json'); and now do delete YourFile.element; reset your elements as YourFile.id = 23; and in the end do a Fs.writeJsonSync('file.json');

Comments

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.