将Oracle查询输出转换为json(Oracle / NodeJS)

nnt7mjpx  于 2022-11-03  发布在  Oracle
关注(0)|答案(2)|浏览(1084)

我正在用React / Express(NodeJS)/ Oracle开发一个应用程序,
我有一个从Oracle表中获取数据的快速路由,
下面是路由中的部分代码:

let conn;
  try {
conn = await oracledb.getConnection(config);
const result = await conn.execute("select  JSON_OBJECT ('departement' VALUE departement, 'ufh' VALUE ufh, 'libelle' VALUE libelle, 'nomhopital' VALUE nomhopital, 'typeservice' VALUE typeservice, 'actif' VALUE actif)  from Z_SOUPAP2CARTESITE where actif=1");

res.send(result.rows);
}

但当我在浏览器中浏览路线时,数据具有以下形状:

[["92","028X362","ABC ACCUEIL URG MEDECINE","ANTOINE BECLERE","ADULTE",1],["92","028X472","ABC URGENCES PEDIATRIQUE","ANTOINE BECLERE","PEDIATRIE",1],["92","014X545","APR ACCEUIL URGENCES ADU","AMBROISE PARE","ADULTE",1]]

我想要这个:

[
  {"departement":"92","ufh":"028X362","libelle":"ABC ACCUEIL URG MEDECINE","nomhopital":"ANTOINE BECLERE","typeservice":"ADULTE","actif":1},
  {"departement":"92","ufh":"028X472","libelle":"ABC URGENCES PEDIATRIQUE","nomhopital":"ANTOINE BECLERE","typeservice":"PEDIATRIE","actif":1}
]
vyswwuz2

vyswwuz21#

为什么要使用JSON_VALUE?驱动程序返回本地JavaScript对象。可以将查询编写为:

select department "department",
  ufh "ufh",
  libelle "libelle",
  nomhopital "nomhopital",
  typeservice "typeservice"
from Z_SOUPAP2CARTESITE 
where actif=1

在上面的查询中,用双引号括起来的列别名用于控制键的大小写。
默认情况下,驱动程序返回一个数组的数组(没有键)。如果你想要一个对象的数组,你需要传递一个选项对象给execute,它会改变outFormat。请参阅文档的这一部分:https://oracle.github.io/node-oracledb/doc/api.html#queryoutputformats
下面是文档中的一个示例:

const result = await connection.execute(
  `SELECT department_id, department_name
   FROM departments
   WHERE manager_id < :id`,
  [110],  // bind value for :id
  { outFormat: oracledb.OUT_FORMAT_OBJECT }
);

console.log(result.rows);

如果要在Oracle中使用JSON生成函数(如JSON_VALUE),则必须避免双重解析-只需以JSON形式访问字符串。
有关使用Node.js和Oracle数据库构建REST API的更多信息,请参见本系列文章:https://jsao.io/2018/03/creating-a-rest-api-with-node-js-and-oracle-database/

s5a0g9ez

s5a0g9ez2#

下面的解决方案对我很有效:

app.post('/getData', async function (req, res) {
try {
    const result = await connection.execute("SELECT * FORM USER", [], { outFormat: oracledb.OUT_FORMAT_OBJECT });
    // print response in json file: import => const fs = require("fs");
    fs.writeFile("response.json", JSON.stringify(result.rows), err => {
        if (err) throw err;
        console.log('File successfully written to disk');
    });

    res.send({
        data: result.rows,
    });
} catch (err) {
    console.log(err);
}});

相关问题