Home > Blockchain >  Display only certain keys in json response
Display only certain keys in json response

Time:05-03

I'm building a simple API with express and sqlite. I want my GET request to only display certain keys in each JSON object that is displayed in response.

Below is my current code:

router.get('/cars', (req, res) => {
    // TODO GET all cars
    try {
        let sql = 'SELECT * FROM cars'
        let params = []
    
        db.all(sql, params, (err, rows) => {
            if (err) {
              res.status(400).json({"error":err.message});
              return;
            }
            else {
                res.status(200).json({
                    message: 'success',
                    data: rows
                })
            }
        });
    } catch(error) {
        console.log(error.message.red)

        res.status(500).json({
            message: 'Not found.'
        })
    }
})

Right now, the response will display entries from the database with all keys and their values. It looks like this:

{
  "message": "success",
  "data": [
    [
      {
        "car_id": 48,
        "email": "[email protected]",
        "name": "Hernando",
        "year": 2015,
        "make": "Acura",
        "model": "TLX",
        "racer_turbo": 0,
        "racer_supercharged": 0,
        "racer_performance": 2,
        "racer_horsepower": 2,
        "car_overall": 4,
        "engine_modifications": 4,
        "engine_performance": 0,
        "engine_chrome": 2,
        "engine_detailing": 4,
        "engine_cleanliness": 4,
        "body_frame_undercarriage": 2,
        "body_frame_suspension": 4,
        "body_frame_chrome": 2,
        "body_frame_detailing": 2,
        "body_frame_cleanliness": 2,
        "mods_paint": 2,
        "mods_body": 2,
        "mods_wrap": 0,
        "mods_rims": 4,
        "mods_interior": 4,
        "mods_other": 4,
        "mods_ice": 6,
        "mods_aftermarket": 2,
        "mods_wip": 0,
        "mods_overall": "4",
        "score": 62
      },
...

I just want to display the car_id, email, name, year, make, model, and score keys and their values and omit the rest of the keys.

I've tried using a forEach loop like so

if(err) {
  res.status(400).json({'error':err.message});
  return;
} else {
  res.json({
    message:'success',
    data: rows.forEach((row) => {
      row.car_id,
      row.email,
      row.name,
      row.year,
      row.make,
      row.model,
      row.score
    }
  })
}

But it doesn't show the data, but I'm not getting any errors in my console either.

Expected output is this:

"message": "success",
  "data": [
    [
      {
        "car_id": 48,
        "email": "[email protected]",
        "name": "Hernando",
        "year": 2015,
        "make": "Acura",
        "model": "TLX",
        "score": 62
      },
...

Any help is really appreciated.

CodePudding user response:

try this

let sql = 'SELECT car_id,email,name,year,make,model,score FROM cars'
  • Related