我如何 return json 被 {} 而不是 [] 包围 Node.js(express) returning 使用 knex 和 postgresql 的查询结果
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) 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"}}
我的模型 "event" 文件是这样的,它对 knex 进行查询,然后 return 结果:
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 对象列表,而不是像现在 returning 那样被 [] 包围?非常感谢
编辑:这解决了我的问题,最终格式为 {"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 请求是 return 对象数组
arrayOfObjects = [
{objkey: objvalue},
{objkey: objvalue}
]
您可以像这样将数组嵌套在对象中
newObj = {
nestedarray: result
}
或者您可以return将对象作为单独的值
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);
});
});
请注意,在这两个选项中,您最终都不会得到所需的格式,这仅仅是因为这是不可能的,但任一选项都摆脱了数组语法。
假设您想单独处理每个对象,您可以使用:
for (i in result){
console.log(result[i]);
}
那将 return,对于您提供的示例:
{"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。
在 JSON 中,[]
方括号包围着数组。您的查询 return 是一个数组,而在您的行 return res.json(result)
中,结果变量是一个数组。将其设为 return 单个对象而不是数组,[]
将消失。如果您希望查询包含多个结果但仍然不需要数组,请将数组包装在另一个对象中,例如 {newResult: result}
和 return。
如果我对我的 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"}}
我的模型 "event" 文件是这样的,它对 knex 进行查询,然后 return 结果:
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 对象列表,而不是像现在 returning 那样被 [] 包围?非常感谢
编辑:这解决了我的问题,最终格式为 {"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 请求是 return 对象数组
arrayOfObjects = [
{objkey: objvalue},
{objkey: objvalue}
]
您可以像这样将数组嵌套在对象中
newObj = {
nestedarray: result
}
或者您可以return将对象作为单独的值
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);
});
});
请注意,在这两个选项中,您最终都不会得到所需的格式,这仅仅是因为这是不可能的,但任一选项都摆脱了数组语法。
假设您想单独处理每个对象,您可以使用:
for (i in result){
console.log(result[i]);
}
那将 return,对于您提供的示例:
{"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。
在 JSON 中,[]
方括号包围着数组。您的查询 return 是一个数组,而在您的行 return res.json(result)
中,结果变量是一个数组。将其设为 return 单个对象而不是数组,[]
将消失。如果您希望查询包含多个结果但仍然不需要数组,请将数组包装在另一个对象中,例如 {newResult: result}
和 return。