nodejs vertica return 查询为 json

nodejs vertica return query as json

我正在创建一个 nodejs express API 使用 node-vertica 查询 Vertica 数据库。我可以 return 结果,但如何 convert/serialize json 格式的结果?现在,结果正在 returned 字段和行中。此外,当我注释掉我的连接关闭时,查询结果将不再显示在浏览器中。这是我的 connection/query。非常感谢任何帮助,如果有比 node-vertica 更好的支持模块,请告诉我。

var express = require('express');
var router = express.Router();
Vertica = require('vertica');

var dbConfig = require('../secrets/dbconfig.js');

var config = {
  ssl: 'optional',
  interruptible: true,
  host: 'xxxx',
  user: dbConfig.iqi_user,
  password: dbConfig.iqi_password,
  database: dbConfig.iqi_DBname
};

try {
  conn = Vertica.connect(config, (err, conn) => {
    if (err) {
      console.log('error');
    } else {
      //console.log(conn);

      router.get('/', (req, res, next) => {
        conn.query('SELECT * FROM LTE_USID_CQI_2018 LIMIT 5', (err, result) => {
          if (err) throw 'hello' + err;
          res.send(result);
        });
      });
      //conn.disconnect();
    }
  });
}
catch (error) {
  console.log("Error has been caught");
  console.log(error);
}

module.exports = router;

示例输出:

{
   "fields":[
      {
         "name":"PERIOD_START_DATE",
         "tableOID":982487324,
         "tableFieldIndex":1,
         "typeOID":10,
         "type":"date",
         "size":8,
         "modifier":4294967295,
         "formatCode":0
      }
   ],
   "rows":[
      [
         "2018-01-01",
         "2018-01-01",
         "Arkansas/Oklahoma",
         "Arkansas",
         14465,
         -1.666162554,
         -0.000055538882,
         -0.00022931,
         -0.001442423085,
         -13.171986306,
         -72.151515449,
         -48.595225949,
         394158,
         396860,
         2905,
         396237,
         397289,
         397733.4534914,
         2968127857,
         590818.977,
         102111.1,
         854609.1,
         133655950,
         1606446,
         27898.3106060606
      ]
   ],
   "notices":[

   ],
   "status":""
}

嗨 rf 家伙,很抱歉回复晚了

这是将结果转换为标准 json 的片段。

const res = {
  "fields": [{
    "name":" PERIOD_START_DATE"
  }, {
    "name": "STATE"
  }, {
    "name": "VALUE"
  }],
  "rows": [
    [
      "2018-01-01",                  
      "Arkansas",
      11111,         
    ], [
      "2019-01-01",                  
      "Oklahomo",
      22222,         
    ]
  ]
}
 
function mapToJSON(dbResult) {
  const fieldNames = dbResult.fields.map(field => field.name) // List of all field names
    
  return dbResult.rows.map(row => {   
    return row.reduce((obj, item, index) => {
      const header = fieldNames[index]
      obj[header] = item
      return obj
    }, {})    
   })
}

const ans = mapToJSON(res)

console.log(ans)
  

在你的代码中你可以做类似的事情

res.send(mapToJSON(result));

甚至更好,因为您使用的是 Express

res.json(mapToJSON(result));

此致 伯格