How to return a complex JSON response with Node.js? How to return a complex JSON response with Node.js? express express

How to return a complex JSON response with Node.js?


On express 3 you can use directly res.json({foo:bar})

res.json({ msgId: msg.fileName })

See the documentation


I don't know if this is really any different, but rather than iterate over the query cursor, you could do something like this:

query.exec(function (err, results){  if (err) res.writeHead(500, err.message)  else if (!results.length) res.writeHead(404);  else {    res.writeHead(200, { 'Content-Type': 'application/json' });    res.write(JSON.stringify(results.map(function (msg){ return {msgId: msg.fileName}; })));  }  res.end();});


[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.

Roughly (untested):

app.get('/users/:email/messages/unread', function(req, res, next) {  var firstItem=true, query=MessageInfo.find(/*...*/);  res.writeHead(200, {'Content-Type': 'application/json'});  query.each(function(docs) {    // Start the JSON array or separate the next element.    res.write(firstItem ? (firstItem=false,'[') : ',');    res.write(JSON.stringify({ msgId: msg.fileName }));  });  res.end(']'); // End the JSON array and response.});

Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:

// ...var query = MessageInfo.find(/*...*/);res.writeHead(200, {'Content-Type': 'application/json'});res.end(JSON.stringify(query.map(function(x){ return x.fileName })));