Sending JSON
The Industry Standard
Section titled “The Industry Standard”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().
Modern Digital Cargo
Section titled “Modern Digital Cargo”
Fig 1: Delivering structured data.
res.json()
Section titled “res.json()”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:
- Converts our JavaScript object/array into a JSON string.
- Sets the
Content-Typeheader toapplication/jsonautomatically.
Simulating a Database (Loading from Disk)
Section titled “Simulating a Database (Loading from Disk)”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.
Extra Bits & Bytes
Section titled “Extra Bits & Bytes”Express Load, Parse, Send JSON - Demo Repo
Express API: res.json()