0
0
Expressframework~5 mins

res.json for JSON responses in Express

Choose your learning style9 modes available
Introduction

res.json sends data as JSON from a server to a client. It helps share information in a simple, readable way.

When you want to send data from your Express server to a web page or app.
When building APIs that return data for other programs to use.
When you want to send error messages or status updates in a clear format.
When you want to share lists, objects, or any structured data easily.
When you want to respond to a client request with JSON instead of HTML.
Syntax
Express
res.json(data)

data can be any JavaScript object or array.

This method automatically sets the response header Content-Type to application/json.

Examples
Sends a JSON object with a message property.
Express
res.json({ message: 'Hello, world!' })
Sends a JSON array of numbers.
Express
res.json([1, 2, 3])
Sends a nested JSON object with success status and user data.
Express
res.json({ success: true, data: { id: 5, name: 'Alice' } })
Sample Program

This Express server listens on port 3000. When you visit /greet, it sends a JSON response with a greeting message.

Express
import express from 'express';
const app = express();

app.get('/greet', (req, res) => {
  res.json({ greeting: 'Hello from Express!' });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

res.json converts your JavaScript object to a JSON string automatically.

It also ends the response, so you don't need to call res.end() after.

Use res.json to make your API responses easy to read and use by other programs.

Summary

res.json sends JSON data from server to client.

It sets the right headers and formats data automatically.

Use it to share data clearly in APIs or web apps.