JSON return format - NODE

Asked

Viewed 33 times

0

I am mounting the REST API in Node, already closed the connections with Oracle and is working, however I need a JSON return different from the way being returned

Currently he’s returning me this way:

   "a": {
      "metaData": [
         {
            "name": "CODCID"
         },
         {
            "name": "CODBAI"
         },
         {
            "name": "CODEND"
         }
      ],
      "rows": [
         [
            25,
            73,
            284
         ]
      ]
   }
}

But I need it to be returned in the form below

[{"codcid":25,"codbai":73,"codend":284}]

My Code is as follows:

async function getCep(req, res, cep) {

    try {
        connection = await oracledb.getConnection({
            user: _user,
            password: _password,
            connectString: _connectString
        });
        console.log('connected to database');
        let query = 'SELECT CODCID,CODBAI,CODEND FROM TSICEP  WHERE CEP = :cep';
        result = await connection.execute(query, [cep]);

    } catch (err) {
        //send error message
        return res.send(err.message);
    } finally {
        if (connection) {
            try {
                
                connection.close();
            } catch (err) {
                return console.error(err.message);
            }
        }
        if (result.rows.length == 0) {
           return res.send('query send no rows');
        } else {
           res.setHeader('Content-Type', 'application/json');
           res.end(JSON.stringify({ result }, null, 3));
        }
    }
}
  • Which database lib you are using?

  • opa, I’m using oracledb

  • Instead of returning the database data right away, do a treatment... Only do normal object manipulation in js

1 answer

0

could solve, by default oracledb returns an array to change this, I made the following change.

result = await Connection.execute(query, [cep],{ outFormat: oracledb.OUT_FORMAT_OBJECT });

Obg

Browser other questions tagged

You are not signed in. Login or sign up in order to post.