nodejs vertica返回查询为json

时间:2018-11-26 22:21:40

标签: node.js api express vertica

我正在创建一个使用node-vertica查询Vertica数据库的nodejs express API。我可以返回结果,但是如何以json格式转换/序列化结果?现在,结果正在返回字段和行。另外,当我注释掉我的连接关闭时,查询结果将不再显示在浏览器中。这是我的连接/查询。非常感谢您的帮助,如果有比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":""
}

1 个答案:

答案 0 :(得分:1)

您好,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));

最好的问候 卑尔根