George
George

Reputation: 1499

Output only JSON values using NodeJS Express for an API

I'm creating an API using NodeJS and Express and can create my JSON response after querying my database. I want to minimize the size of the response and only output the values and not the keys. Here is the response I am creating.

const api = (req, res) => {
    pool.query(query, (err, response) => {
        if (err){
        }
    res.status(200).json(response.rows);
})

The response from the query is a simple table (I'm omitting columns to simplify).

Time Values
1 50
2 40
3 70
4 10

The actual JSON response is:

[{"time":1,"Values":"50"},{"time":2,"Values":"40"},{"time":3,"Values":"70"},{"time":4,"Values":"10"}]

My target output is:

[[1,50],[2,40],[3,70],[4,10]]

Is there a simple option to change with this line?

res.status(200).json(response.rows);

Or do I need to manipulate the response form the query to remove the column headers? I'm using Postgres and not sure how I would do that?

Upvotes: 0

Views: 705

Answers (2)

Saydur Rahman
Saydur Rahman

Reputation: 74

I don't know what the data type of response.rows is
It the data type of response.rows is JSON then, convert this to Object type

const responseRows = JSON.parse(response.rows);

If the data type of response.rows is object then, not need to do anything

const responseRows = response.rows;

at this point your response.rows is an object

const actResponse = responseRows.map(el => {
 return[ el.time, Number(el.Values) ]
});
res.status(200).json(actResponse);

Upvotes: 2

Evert
Evert

Reputation: 99717

response.rows.map( row => {
  return [row.Time, +row.Values];
});

Upvotes: 2

Related Questions