Since JSON is very popular, people tend to use that heavily in web services. In this article we will see how to send JSON response using express and node js.

The response object has a function json() that converts the given input/ argument into JSON format and send as response.

Example – Express Send JSON Response

Below is a simple example where we directly supply a JSON as an argument to res.json() function.

app.get('/hello',function(req,res){
	res.json({Firstname:"My Name"});
});

Now, let us see how to construct a JavaScript object and send that as JSON.

var express = require("express");
var app = express();
app.get('/hello',function(req,res){
    var myJson = {};
    myJson.name = "First Name";
    myJson.properties = {age : 25};
	res.json(myJson);
});
app.listen(8080);

Run the above code to create a GET service and make a request to it. Use postman or browser to invoke the url http://localhost:8080/hello.
Response:

{
  "name": "First Name",
  "properties": {
    "age": 25
  }
}

Check the response properties and you will be able to see that the content type is automatically set as “application/json”.

Express Send JSON Response