Skip to content

Sending JSON

In the modern web stack, we barely send HTML files from the server anymore. We send raw data, and the client (React, Vue, mobile app) renders it. The standard container for this data is JSON.

Express makes this exceedingly easy. Instead of res.send(), we use res.json().

A futuristic armored transport truck speeding down a neon highway. The back is open revealing glowing cubes of JSON data.

Fig 1: Delivering structured data.

app.get('/api/user', (req, res) => {
const user = {
name: 'Han Solo',
ship: 'Falcon',
parsecs: 12,
};
// The Gold Standard
res.json(user);
});

res.json() does two important things:

  1. Converts our JavaScript object/array into a JSON string.
  2. Sets the Content-Type header to application/json automatically.

Real apps use databases, but for learning, a JSON file is a great substitute. We can use what we learned in the previous lessons (path and file reading) to serve “dynamic” data.

const fs = require('fs');
const path = require('path');
app.get('/api/inventory', (req, res) => {
// 1. Find the file
const filePath = path.join(__dirname, 'data', 'inventory.json');
// 2. Read the file
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
// Always handle your errors!
return res.status(500).send('Database System Failure');
}
// 3. Parse and Send
const inventory = JSON.parse(data);
res.json(inventory);
});
});

This pattern—Read, Parse, Send—is the grandfather of all API logic.


Express Load, Parse, Send JSON - Demo Repo

Express API: res.json()

⏭ The Checkpoints

We’ve mastered delivery. Now let’s talk about security and the Middleware Stack.