Fredrik_Swe
Fredrik_Swe

Reputation: 13

Get specific JSON object with node.js

I want to be able to type localhost:3000/courses/1 and be able to get to show only the object in the json file from the id: 1.

I have a route to the site courses that looks like this and it displays my JSON file in the view when i loop through it just as it should. The js:json is my JSON file that I have required.

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

[
{
"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
}
]

But how can i make a route to show only one specific part of the JSON file when i type localhost:3000/courses/1 or /2 or /3?

So that the view looks like this..

 "id":1,"courseId":"DT162G","courseName":"Javascript-baserad webbutveckling","coursePeriod":1

Upvotes: 0

Views: 3127

Answers (2)

Khalid
Khalid

Reputation: 4808

you may need to add a parameter to your route

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

then a simple function that returns your object

function getData (id) { 
   if(typeof id == "undefined") {
       return json;
   }

   for(var i in json) { 
      if(json[i].id == id) {
         return json[id];
      }
   }
}

Upvotes: 0

ram hemasri
ram hemasri

Reputation: 1634

app.get('/courses/:id', function(req, res) {
    res.render('courses', {
        title: "Hello",
        name: "Fredrik",
        js: req.params.id !== undefined ? json.filter(function(obj) {return obj.id== req.params.id};}) : json
    });
});

Upvotes: 1

Related Questions