Subburaj
Subburaj

Reputation: 5192

Json response + Node.js

In my node app i pass bunch of queries as Object.I have to form as exact format of request.

Consider my request as:

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

My reponse should be {q0:{response0},q1{response1},q2{response2}

My actual query(In my app):

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

But my response is coming as:

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

My code:

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

Please help me to solve this..Thanks in advance.

Upvotes: 0

Views: 80

Answers (1)

Saravana Kumar
Saravana Kumar

Reputation: 836

You are pushing the result in an array instead you should create a property in the result object as below

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

Upvotes: 1

Related Questions