2014-01-16 43 views
0

在我的節點應用程序中,我傳遞了一堆查詢,因爲Object.I必須形成請求的確切格式。Json響應+ Node.js

考慮我的請求爲:

{q0:{query0},q1:{query1},q2:{query1}} 

我的效應初探應該{q0:{response0},q1{response1},q2{response2}

我的實際查詢(在我的應用程序):

{"q0":{"query":"James Madison","type":"/people/presidents","type_strict":"should"}, 
"q1":{"query":"George Washington","type":"/people/presidents","type_strict":"should"}, 
"q2":{"query":"John Adams","type":"/people/presidents","type_strict":"should"}, 
"q3":{"query":"James Monroe","type":"/people/presidents","type_strict":"should"}, 
"q4":{"query":"Thomas Jefferson","type":"/people/presidents","type_strict":"should"}} 

但我的回答是如來:

{"result":[q0result,q1result,q3result]} 

我的代碼:

for (var id in presidents) { 
     var match 
     if (query == presidents[id]) { 
     //console.log(" Inside match") 
      match = true; 
     } 
     else { 
      match = false; 
     } 
     matches.push({ 
      "id": id, 
      //"name": name, 
      "score": 100, 
      "match": match, 
      "type": [{ 
       "id": "/people/presidents", 
       "name": "US President" 
      }] 
     }) 
    } 
    callback(matches); 



json = JSON.stringify({"result":matches}); 
    res.writeHead(200, {'content-type':'application/json'}); 
    res.end(json); 

請幫我解決這個問題..預先感謝。

回答

1

你正在推動在一個數組的結果,而不是你應該建立在結果對象的屬性如下

var matches = {}; 
for (var id in presidents) { 

     if (query == presidents[id]) { 
     //console.log(" Inside match") 
      match = true; 
     } 
     else { 
      match = false; 
     } 
     matches[id] ={ 
      "id": id, 
      //"name": name, 
      "score": 100, 
      "match": match, 
      "type": [{ 
       "id": "/people/presidents", 
       "name": "US President" 
      }] 
     }; 
    } 
    callback(matches); 
+0

謝謝@Saravana庫馬爾..its僅返回1個結果.. – Subburaj

+0

你之前宣佈比賽循環,請參閱編輯的答案 –