2016-07-23 31 views
2

http://127.0.0.1:3000/api/events/user/id/1我得到這樣的結果:如何在Node.js(express)上返回由{}代替[]而不是[]的json如果我對我的node.js(EXPRESS)API curl執行了curl請求,則返回使用knex和postgresql的查詢結果

[{"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:[email protected]: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對象名單現在回來了嗎?非常感謝您

編輯:這解決了我的問題,最終的格式爲{ 「行」:[{ROW1},{ROW2}等]}

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; } 
+0

爲什麼你需要那個確切的輸出(這是無效的)?你也可以回答你將要輸出的內容嗎?爲什麼數組[{},{}]或數組外觀對象{1:{},2:{}}不適合? – iovoid

回答

2

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

    }); 
}); 

注意,在這兩個選項,你不想要,只是因爲它是不可能的格式結束,但任一選項擺脫了數組語法。

+0

謝謝,但是你能給出一些關於在這個特定情況下如何做到這一點的代碼規範嗎?......我明白你在說什麼,但我需要知道實現,而不是理論方面的事情...... 。因爲我使用這個knex庫查詢postgres DB,我不知道如何以這種格式返回東西....我只想{{object1},{object2},{object3}}格式 – Juan

+0

我的意思是,我don'twant格式 {[ {} object1, {} Object2的 ] } 這是你用{}結束工作提出什麼....只是 {{ },{},{}} – Juan

+0

選項二提供了一個對象:{1:{},2:{} ...} – alexi2

0

Asuming要處理的每個對象分別可以使用:

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

注:{{東西:1}},正如你提出的想要的輸出,不是有效的JSON。

0

在JSON中,[]括號包圍陣列。您的查詢返回一個數組,並且在您的行return res.json(result)中,結果變量是一個數組。讓它返回一個單獨的對象而不是一個數組,並且[]將會消失。如果您希望查詢包含多個結果並且仍然不想要數組,請將數組包裝在另一個對象中,如{newResult: result},然後返回該結果。

+0

謝謝,你的回答也很有幫助,但Alexi2試圖意識到我想要的東西是不可能的,並給出了有效的選擇,所以我會接受他的回答,但我結束了做這個.......非常感謝你! – Juan

相關問題