json - 如何在 Node.js(express) 上返回由 {} 而不是 [] 包围的 json 返回使用 knex 和 postgresql 的查询结果

标签 json node.js express knex.js

如果我向我的node.js(EXPRESS) APIcurl发出curl请求http://127.0.0.1:3000/api/events/user/id/1我得到这个结果:

[{"id":"1","name":"casamiento 1","description":"el casamiento del tio claudio","mode_id":1,"initial_date":"2016-05-28T22:14:57.000Z","end_date":"2016-05-28T22:14:58.000Z","state_id":1,"user_id":"1","location":"0101000020E61000000000000000805BC00000000000003E40"},{"id":"2","name":"casamiento 2","description":"el casamiento del tio claudio 2","mode_id":1,"initial_date":"2016-05-28T22:14:57.000Z","end_date":"2016-05-28T22:14:58.000Z","state_id":1,"user_id":"1","location":"0101000020E61000000000000000405BC00000000000003D40"},{"id":"3","name":"fiesta del sandwich de miga","description":"Nos juntamos a comer sandwiches de miga hasta reventar","mode_id":1,"initial_date":"2016-05-28T22:15:58.000Z","end_date":"2016-05-28T22:15:58.000Z","state_id":1,"user_id":"1","location":"0101000020E610000000000000000000000000000000804840"}]

我需要将输出用大括号括起来,例如:

 {{"id":"1","name":"casamiento 1","description":"el casamiento del tio claudio","mode_id":1,"initial_date":"2016-05-28T22:14:57.000Z","end_date":"2016-05-28T22:14:58.000Z","state_id":1,"user_id":"1","location":"0101000020E61000000000000000805BC00000000000003E40"},{"id":"2","name":"casamiento 2","description":"el casamiento del tio claudio 2","mode_id":1,"initial_date":"2016-05-28T22:14:57.000Z","end_date":"2016-05-28T22:14:58.000Z","state_id":1,"user_id":"1","location":"0101000020E61000000000000000405BC00000000000003D40"},{"id":"3","name":"fiesta del sandwich de miga","description":"Nos juntamos a comer sandwiches de miga hasta reventar","mode_id":1,"initial_date":"2016-05-28T22:15:58.000Z","end_date":"2016-05-28T22:15:58.000Z","state_id":1,"user_id":"1","location":"0101000020E610000000000000000000000000000000804840"}}

我的模型“事件”文件是这样的,它对 knex 进行查询,然后返回结果:

var express = require('express');
var router = express.Router();
var Promise = require("bluebird");
var connectionString = 'postgres://postgres:postgres@localhost:5432/flock';
var knex = require('knex')({
  client: 'pg',
  connection: connectionString,
  searchPath: 'knex,public'
});

//Get all events from a particular user
exports.getUserEvents=function(id_user){



    console.log("Retrieving data from id_user: "+id_user);

    var promise1 = Promise.try(function () {
    return knex('events')
      .select('*')
      .where('user_id', id_user);
     });

    var promise2=promise1.then(function (rows) { // this creates a new promise, and the promise created here is what gets returned to the caller
      console.log('Returning '+rows.length+' rows from the user with id '+id_user);
      return rows;

    });

    return promise2;
}

我的路由器文件调用模型文件函数 getUserEvents,如下所示:

var express = require('express');
var router = express.Router();
var Event=require('../models/event');


//get all events from a user

router.get('/user/id/:id_user', function(req, res, next) {

   var id_user= req.params.id_user;

   var promise = Event.getUserEvents(id_user);

    promise.then(function (result) {
     console.log('Sending response');
     return res.json(result);  //<---this line builds the JSON response
   });

   promise.catch(function (err) {


     return res.sendStatus(500); 

   });

});




module.exports = router

我的问题是,如何发送由 {} 包围的 json 对象列表,而不是像现在返回的那样由 [] 包围?。非常感谢

编辑:这解决了我的问题,最终格式是 {"rows":[{row1},{row2},etc]}

exports.getUserEvents=function(id_user){



    console.log("Retrieving data from id_user: "+id_user);

    var promise1 = Promise.try(function () {
    return knex('events')
      .select('*')
      .where('user_id', id_user);
     });

    var promise2=promise1.then(function (rows) { // this creates a new promise, and the promise created here is what gets returned to the caller
      console.log('Returning '+rows.length+' events from the user with id '+id_user);
      return {rows};//<----This solved the issue

    });

    return promise2; }

最佳答案

您的 API 请求正在返回对象数组

arrayOfObjects = [
    {objkey: objvalue},
    {objkey: objvalue}
]

您可以将数组嵌套在这样的对象中

newObj = {
    nestedarray: result
}

或者您可以将对象作为单独的值返回

newObj = {
    1: result[0],
    2: result[1],
    3: result[2]
}

但是所有对象都需要一个键值对。

请注意,Javascript 中的数组实际上是一种特殊类型的对象,它仍然使用恰好是整数的属性名称,但经过优化以允许特殊方法。

所以在你的情况下:

var express = require('express');
var router = express.Router();
var Event=require('../models/event');


//get all events from a user

router.get('/user/id/:id_user', function(req, res, next) {

    var id_user= req.params.id_user;

    var promise = Event.getUserEvents(id_user);

    promise.then(function (result) {
    console.log('Sending response');

    // Option One
    var newObj = {
        nestedarray: result
    }

    // Option Two
    var newObj = {}
    response.forEach(function(elem, index) {
        newObj[index] = elem;
    });

    return res.json(newObj);  //<---this line builds the JSON response
});

   promise.catch(function (err) {

        return res.sendStatus(500); 

   });
});

请注意,在这两个选项中,您最终都不会得到所需的格式,因为这是不可能的,但任一选项都摆脱了数组语法。

关于json - 如何在 Node.js(express) 上返回由 {} 而不是 [] 包围的 json 返回使用 knex 和 postgresql 的查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38537226/

相关文章:

mysql - 类型错误 : Cannot read property 'findOne' of undefined while using sequelize in node

javascript - 如何检查 Node JS 服务器端代码中是否启用了 javascript

node.js - 为 Node/Express/Typescript 和 Angular 设置一个项目

mysql格式化mysql结果满足json handsontable

java - XML 到 JSON - 丢失根节点

json - 如何强制 Servant 返回 JSON 错误而不是纯字符串?

MySQL 查询在 NodeJS 中返回 [Object, object],为什么?

python - JSON - 在 python 中循环生成 json

node.js - SequelizeJS,这是使用此模型创建此 JSON 结果的最佳方法吗

node.js - 使用 salt n hash 和 postgresql 中的登录角色登录详细信息安全性