Lesson 11
Generating JSON Text from Values
Serialization, key order, and keeping output stable for tests and APIs.
Generation (serialization) walks your in-memory values and writes JSON text—for HTTP responses, file exports, or test fixtures. It is the inverse of parsing, with its own design choices.
Default behavior varies
Most serializers:
- Omit
undefinedproperties (JavaScript) or require explicit null handling - Escape strings automatically
- Write numbers in decimal form
Example conceptually:
{"status": "ok", "count": 3}
from an object with status and count fields.
Key order and stable output
Object key order is not semantically significant in JSON, but serialized byte order is significant for:
- Git diffs and snapshot tests
- Cryptographic signatures over raw bytes
- Cache keys built from canonical JSON
Teams sometimes sort keys alphabetically before generating text so two logically equal objects produce identical strings.
Pretty vs compact generation
| Mode | Use when |
|---|---|
| Pretty (indented) | Human review, docs, debug |
| Compact | Wire transfer, storage size matters |
The same data can be valid in both forms—choose based on audience, not correctness.
Round-trip thinking
Ideal flow: values → text → parse → equal values. Floating-point numbers, large integers, or custom types (dates, BigInt) may not round-trip perfectly unless you define conventions (ISO date strings, string-encoded decimals).
Document those conventions in API specs so clients and servers agree.