Serving JSON
Serving JSON means sending data in JSON form from a server. JSON is a text form of an object that other programs can read.
Turn an object into JSON
This line prints the object as a JSON text.
console.log(JSON.stringify({ name: 'Asha' }));Name the kind of data
This line marks the reply as JSON data.
res.writeHead(200, { 'Content-Type': 'application/json' });Example
const http = require('http');
const user = { name: 'Asha', age: 28 };
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(user));
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});Key points
- JSON is a text form of an object that other programs can read.
- JSON.stringify turns an object into a JSON text.
- The Content-Type header names the kind of data in a reply.
- The value application/json names JSON data.
- The reply is plain text that a program can read as data.
- Use JSON when a server sends data instead of a page.
In this example, user holds one object with a name and an age. The server turns that object into JSON text. A visit to the server answers {"name":"Asha","age":28}. The startup line prints Server running on port 3000.
Note
JSON keys and string values always use double quotes.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which header value marks a reply as JSON?