【问题标题】:How to reformat oracledb json output?如何重新格式化 oracledb json 输出?
【发布时间】:2018-04-13 17:57:36
【问题描述】:

使用带有 outFormat:oracledb.OBJECT 选项的 oracledb node.js 驱动程序返回 json,但列名格式为大写(属性名遵循 Oracle 的标准名称大小写规则),如下所示: {"ID":"1"} 是否可以将它们设为小写,如下所示: {"Id":"1"}?

Oracle 数据库 12.2 中引入的 JSON_OBJECT 对我不可用。

【问题讨论】:

    标签: node.js oracle node-oracledb


    【解决方案1】:

    只需使用列别名:

    const oracledb = require('oracledb');
    const config = require('./dbConfig.js');
    
    (async function() {
      let conn;
      let result;
    
      try {
        conn = await oracledb.getConnection(config);
    
        result = await conn.execute(
         `select first_name || ' ' || last_name name,
            email
          from employees
          where rownum = 1`,
          [], // no binds
          {
            outFormat: oracledb.OBJECT
          }
        );
    
        // This is the problem, uppercase column names, no?
        console.log(result.rows); // [ { NAME: 'Steven King', EMAIL: 'SKING' } ]
    
        result = await conn.execute(
         `select first_name || ' ' || last_name "name",
            email "email"
          from employees
          where rownum = 1`,
          [], // no binds
          {
            outFormat: oracledb.OBJECT
          }
        );
    
        // Here's the result with case sensitve aliases
        console.log(result.rows); // [ { name: 'Steven King', email: 'SKING' } ]
      } catch (err) {
        // Will throw, but only after finally runs
        throw err; 
      } finally {
        if (conn) {
          try {
            await conn.close();
          } catch (err) {
            console.log('error closing conn', err);
          }
        }
      }
    }());
    

    或“处理”之后的结果。您可能会发现这很相关: https://jsao.io/2015/07/relational-to-json-with-node-js/

    【讨论】:

    • 谢谢,但是当使用 connection.execute("SELECT realcolumnname "id" FROM sometable",{}...) 时收到状态 500。
    • 你有一个名为 sometable 的表吗?这只是一个示例,您需要根据您的环境对其进行调整。关键是使用用双引号括起来的列别名。
    • 当然,我明白了,但正如 9.1.4 中所写,每一行都是一个 JavaScript 对象,它指定列名及其各自的值。请注意,属性名称遵循 Oracle 的标准名称大小写规则。它们通常是大写的,因为大多数应用程序使用不带引号的、不区分大小写的名称创建表。这就是发生的事情,我的目标是克服这个问题。
    • 我已经用一个例子更新了我的答案。这不是你想要做的吗?
    • 谢谢,您的更新正是我想要做的。我只是用错误的引号把 Select 弄得一团糟。
    猜你喜欢
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多