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

Ver*_*ion 1 oracle json node.js express

我正在使用 React / Express (NodeJS) / Oracle 制作一个应用程序,

我有一个从 Oracle 表获取数据的 Express 路线,

这是路线中的部分代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

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

[["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]]
Run Code Online (Sandbox Code Playgroud)

我想要这个:

[
  {"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}
]
Run Code Online (Sandbox Code Playgroud)

Dan*_*han 5

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

select department "department",
  ufh "ufh",
  libelle "libelle",
  nomhopital "nomhopital",
  typeservice "typeservice"
from Z_SOUPAP2CARTESITE 
where actif=1 
Run Code Online (Sandbox Code Playgroud)

在上面的查询中,双引号列别名用于控制键的大小写。

默认情况下,驱动程序返回一个数组的数组(无键)。如果您想要一个对象数组,则需要传递一个选项对象来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);
Run Code Online (Sandbox Code Playgroud)

如果要使用 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 /