2014-01-16 42 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

你之前宣布比赛循环,请参阅编辑的答案 –