Code Snippet - Return JSON Response for Express.js
2014/07/051 min read
bookmark this
Table of Contents
Introduction
This is a sample code snippet for creating an API that returns a JSON object in Express.js.
Sample Code
A Sample Code Snippet for create api return json object
var tagQ = yourCollection.find({}).limit(20);
yourCollection.exec(function (err, resultCollections) {
var array = [];
var result = {};
resultCollections.forEach(function (tag) {
array.push(tag.TagId);
});
result.name = 'name';
result.id = 'id';
result.items = array;
res.json(result);
});
JSON Response
The above code will return a JSON object like the following:
{
"name": "name",
"id": "id",
"items": [
"your item1",
"your item2"
]
}
Conclusion
Using res.json() in Express.js is a simple way to return a JSON response from your API. You can build the response object by querying your collection and structuring the data as needed.