Quiz
Warm-up from lesson 5-3. Why did toPositiveInt(value, fallback) exist at all? What is true of every value arriving in req.query?
The data format of the web
APIs exchange JSON (JavaScript Object Notation): a text format for objects, arrays, strings, numbers, booleans, and null. It looks like JavaScript literals with two extra rules: keys are always double-quoted, and no trailing commas, comments, or functions.
Networks only carry bytes of text, so objects must be converted both ways:
JSON.stringify(obj)turns a live object into a JSON string (to send).JSON.parse(text)turns a JSON string back into an object (to receive).
Express's res.json(obj) calls stringify for you, and express.json() middleware calls parse on incoming bodies. Underneath, it is these two functions.
Code exercise · javascript
Run this round trip: object to wire string, wire string back to object. Note that the parsed copy is a real object again, with working properties and arrays.
Parse can explode
JSON.parse throws an exception on malformed input, and clients send malformed JSON all the time (truncated requests, hand-written curl commands, buggy apps). An unhandled throw in a server means a crashed request, so parsing untrusted text always gets a try/catch:
try { const body = JSON.parse(text); } catch (err) { // respond 400 invalid_input, using the error shape from lesson 4-3 }
A tidy pattern wraps this in a helper that never throws and returns a result object instead. Build it below, this shape ({ ok, value } or { ok, error }) appears all over production Node code.
Code exercise · javascript
Your turn. Implement safeParse(text): return { ok: true, value: parsed } on success, and { ok: false, error: "invalid json" } when JSON.parse throws. The second test input uses an unquoted key, which is legal JavaScript but illegal JSON.
Quiz
A buggy service responds with the header Content-Type: application/json, but the body is the plain text "Hello". Client code calls res.json() on the response. What happens?