Json响应+ Node.js

时间:2014-01-16 06:34:09

标签: json node.js

在我的节点应用程序中,我将一堆查询作为Object传递。我必须将其形成为请求的确切格式。

请将我的请求视为:

{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 个答案:

答案 0 :(得分: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);