【问题标题】:How do I return a json surrounded by {} instead of [] on Node.js(express) returning a result of a query using knex and postgresql如何在 Node.js(express) 上返回由 {} 而不是 [] 包围的 json,返回使用 knex 和 postgresql 的查询结果
【发布时间】:2016-07-23 01:17:18
【问题描述】:

如果我向我的 node.js(EXPRESS) API curl http://127.0.0.1:3000/api/events/user/id/1 发出 curl 请求,我会得到以下结果:

[{"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; }

【问题讨论】:

  • 为什么你需要那个精确的输出(那是无效的)?您能否也回答您要将该输出提供给什么?为什么数组 [{},{}] 或类似数组的对象 {1:{},2:{}} 不合适?

标签: json node.js express knex.js


【解决方案1】:

您的 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); 

   });
});

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

【讨论】:

  • 谢谢,但是你能给出一些代码说明在这种特殊情况下如何做到这一点吗?......我明白你在说什么,但我需要知道实现,而不是理论问题的一面......因为我正在使用这个 knex 库来查询 postgres DB,我不知道如何以这种格式返回东西......我只想要 {{object1},{object2} ,{object3}} 格式
  • 我的意思是,我不想要格式 { [ {object1}, {object2} ] },这就是你提出的用 {} 包装起来的格式......只是 {{}, {},{} }
  • 选项二给你一个对象:{1:{}, 2:{}...}
  • 我不想添加那个索引...我只想要对象本身...... {{"name":name, "last_name":"last_name"} ,{"name":name, "last_name":"last_name"}} 这种格式....问题是我对构建对象没有太多控制权,因为 knex 会这样返回它......我怎样才能实现这种精确的格式?
  • 所有对象都需要一个键值对。您所问的问题在 javascript 或使用 JSON 中都是不可能的。我试图提供一个替代方案。从json.org JSON 建立在两个结构之上:名称/值对的集合。在各种语言中,这被实现为对象、记录、结构、字典、哈希表、键控列表或关联数组。值的有序列表。在大多数语言中,这被实现为数组、向量、列表或序列。
【解决方案2】:

假设您想单独处理可以使用的每个对象:

for (i in result){
  console.log(result[i]);
}

对于您提供的示例,这将返回:

{"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"}
and
{"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"}
and
{"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"}

注意:{{stuff: 1}},正如您提出的所需输出,不是有效的 JSON。

【讨论】:

    【解决方案3】:

    在 JSON 中,[] 括号包围数组。您的查询返回一个数组,在您的return res.json(result) 行中,结果变量是一个数组。使其返回单个对象而不是数组,[] 将消失。如果您希望查询包含多个结果但仍不想要数组,请将数组包装在另一个对象中,例如 {newResult: result} 并返回它。

    【讨论】:

    • 谢谢,你的回答也很有帮助,但 Alexi2 试图意识到我想要的东西是不可能的,并给出了有效的替代方案,所以我会接受他的回答,但我最终这样做了...... ...非常感谢!
    猜你喜欢
    • 2012-07-26
    • 1970-01-01
    • 2021-06-02
    • 2019-07-16
    • 2014-12-04
    • 2013-08-24
    • 2016-01-12
    • 2018-06-18
    相关资源
    最近更新 更多