Part 03 · The Language of the Web
JSON and Serialization
Turning objects in memory into bytes on the wire and back again, safely.
⏱ 1 hours · Station 31 of 153
The order ID that changed by one
A Go backend creates an order with ID 9007199254740993 and returns it as JSON. The web app, written in JavaScript, reads the ID and shows a link to "order 9007199254740992". The customer clicks it: "Order not found".
Nobody wrote a bug in the usual sense. Go wrote the number correctly. JSON carried it correctly. JavaScript read it as a 64-bit floating-point number, which can't represent that integer exactly, and silently rounded it.
Every time your backend sends data, it has to turn objects in memory into bytes (serialization), and the other side has to turn bytes back into its own objects (deserialization). The two sides often use different languages, with different ideas of what a "number" or a "string" is. JSON is the common format on the web, and this lesson is about what it promises, what it doesn't, and where it bites.
The problem: memory can't travel
An object in your program's memory is full of things that mean nothing on another machine:
| In memory | Why it can't just be sent |
|---|---|
| Pointers / references | An address like 0xc000012080 means nothing in another process |
| Language types | A Go struct, a Python dict, a Java record look nothing alike in memory |
| Number layouts | 32/64-bit, big/little endian, int vs float vary between languages and machines |
| Strings | UTF-8 in Go and Rust, UTF-16 inside JavaScript and Java |
| Dates, money, enums | Every language has its own type, or none |
So both sides agree on a format: a way to write values as a sequence of bytes that any language can read back. JSON is a text format with just six kinds of value, which is why every language can handle it, and also why some things get lost.
Think of dictating a shopping list over the phone
You can't send the actual basket of groceries down a phone line. You describe it in words both of you understand: "two pens at twelve and a half taka each, not paid yet, no coupon".
- Your friend writes it down and rebuilds the list on their side, in their own handwriting.
- If you both speak the same language and agree on how to say numbers, the list arrives intact.
- If you say "nine quadrillion and three" and your friend's notebook only has room for 15 digits, the last digit gets smudged.
Serialization is the dictation. JSON is the language. The smudged digit is the floating-point problem from the hook.
Where the analogy stops working. A friend on the phone can ask "did you say thirteen or thirty?". A JSON parser can't; it reads exactly what's written and maps it into its own types, rounding or failing silently if a value doesn't fit. Ambiguity has to be removed before the data is sent.
The building blocks
- JSON has six kinds of value:
null,true/false, numbers, strings, arrays[...]and objects{"key": value}. That's all. No dates, no money type, no binary, no comments, no trailing commas. - Strings are UTF-8 text in double quotes. Inside them,
"becomes\",\becomes\\, newline becomes\n, and other control characters become\u00XX. Non-ASCII text like Bangla can be written directly as UTF-8 or escaped asর; both mean the same. - Numbers have no size or type in the spec.
42,12.5and9007199254740993are all just "number". Each reader decides how to store them. JavaScript always uses 64-bit floats, which are exact only up to 2^53 = 9,007,199,254,740,992. Larger integers (database IDs, Twitter-style snowflake IDs) should be sent as strings. - Floats can't hold most decimals exactly.
0.1 + 0.2is0.30000000000000004. Money should travel as integer minor units ("amount_paisa": 1250) or as a decimal string ("12.50"), never as a float. - Dates have no JSON type. The common convention is an ISO 8601 string in UTC:
"2026-11-20T09:30:00Z". Unix timestamps (seconds or milliseconds) also work, but say which. - Object key order isn't guaranteed, and duplicate keys are undefined behaviour. Don't rely on either.
- Serialization is a boundary. Decide explicitly what goes out (don't dump whole database rows, including password hashes) and validate what comes in (types, ranges, required fields) before using it.
- JSON isn't the only format. Protocol Buffers, MessagePack and Avro are binary: smaller and faster, with a schema, but not human-readable. JSON wins for public APIs because anyone can read and debug it.
Your API returns {"amount": 0.1} and the client adds it three times to show a total. What does a JavaScript client display if it just prints the sum?
Behind the scenes: an order goes from Go to JavaScript
Serialize, send, deserialize
Step 1/5 The order in Go memory
A struct with int64 ID, string customer, slice of items, bool paid, a nil pointer for coupon. Some fields live at memory addresses that mean nothing elsewhere.
- id
- int64 9007199254740993
The picture to keep in your head
Serialization is describing a value in a shared language so the other side can rebuild it:
- The description (JSON text) is exact.
- The rebuilding happens in the reader's own types, and that's where things get rounded, renamed or dropped.
- So design the description for the weakest reader: big IDs as strings, money as integers or decimal strings, dates as ISO strings in UTC, and only the fields you mean to share.
Try it: will this survive the trip?
Safe JSON or a trap?
{"id": 1795139962000123456}Code from first principles
A JSON encoder written by hand in each language: it walks a nested value and writes each of the six kinds of JSON value, escaping strings by the rules and keeping object keys in order. Then two classic pitfalls: a large integer read as a float, and money added as floats versus integer paisa/cents.
package main
import (
"fmt"
"strconv"
"strings"
"unicode/utf8"
)
// A JSON value is one of: nil, bool, int, float64, string, []any (array), or obj (object with ordered keys).
type pair struct {
key string
val any
}
type obj []pair
// encode turns an in-memory value into JSON text, following the JSON rules by hand.
func encode(v any) string {
switch x := v.(type) {
case nil:
return "null"
case bool:
return strconv.FormatBool(x)
case int:
return strconv.Itoa(x)
case float64:
return strconv.FormatFloat(x, 'g', -1, 64)
case string:
var b strings.Builder
b.WriteByte('"')
for _, r := range x {
switch {
case r == '"':
b.WriteString(`\"`)
case r == '\\':
b.WriteString(`\\`)
case r == '\n':
b.WriteString(`\n`)
case r < 0x20: // other control characters
fmt.Fprintf(&b, `\u%04x`, r)
default: // everything else, including Bangla, goes in as UTF-8
b.WriteRune(r)
}
}
b.WriteByte('"')
return b.String()
case []any:
parts := make([]string, len(x))
for i, e := range x {
parts[i] = encode(e)
}
return "[" + strings.Join(parts, ",") + "]"
case obj:
parts := make([]string, len(x))
for i, p := range x {
parts[i] = encode(p.key) + ":" + encode(p.val)
}
return "{" + strings.Join(parts, ",") + "}"
}
panic("not JSON")
}
func main() {
order := obj{
{"id", 42},
{"customer", `রহিম "R"`},
{"items", []any{obj{{"sku", "pen"}, {"qty", 2}, {"price", 12.5}}}},
{"paid", false},
{"coupon", nil},
{"note", "line1\nline2"},
}
text := encode(order)
fmt.Println("json: " + text)
fmt.Printf("size: %d bytes, %d characters\n", len(text), utf8.RuneCountInString(text))
// Pitfall 1: JSON numbers are often read as 64-bit floats (JavaScript always does).
var bigID int64 = 9007199254740993 // 2^53 + 1
fmt.Printf("id %d read as a float64: %.0f\n", bigID, float64(bigID))
// Pitfall 2: money in floats.
a, b := 0.1, 0.2 // variables, so the compiler can't do the sum exactly at compile time
fmt.Println("0.1 + 0.2 as float64:", strconv.FormatFloat(a+b, 'g', -1, 64))
cents := 10 + 20
fmt.Printf("10 + 20 as integer cents: %d -> \"%d.%02d\"\n", cents, cents/100, cents%100)
}// A JSON value is one of: null, boolean, integer, float, string, array, or object (ordered keys).
// Numbers are tagged so integers and floats are written the same way as in the other languages.
const int = (n) => ({ int: n });
const float = (n) => ({ float: n });
const obj = (...pairs) => ({ pairs });
// encode turns an in-memory value into JSON text, following the JSON rules by hand.
function encode(v) {
if (v === null) return "null";
if (typeof v === "boolean") return String(v);
if (typeof v === "string") {
let out = '"';
for (const ch of v) {
const code = ch.codePointAt(0);
if (ch === '"') out += '\\"';
else if (ch === "\\") out += "\\\\";
else if (ch === "\n") out += "\\n";
else if (code < 0x20) out += "\\u" + code.toString(16).padStart(4, "0"); // other control characters
else out += ch; // everything else, including Bangla, goes in as UTF-8
}
return out + '"';
}
if (Array.isArray(v)) return "[" + v.map(encode).join(",") + "]";
if ("int" in v) return String(v.int);
if ("float" in v) return String(v.float);
return "{" + v.pairs.map(([k, val]) => encode(k) + ":" + encode(val)).join(",") + "}";
}
const order = obj(
["id", int(42)],
["customer", 'রহিম "R"'],
["items", [obj(["sku", "pen"], ["qty", int(2)], ["price", float(12.5)])]],
["paid", false],
["coupon", null],
["note", "line1\nline2"],
);
const text = encode(order);
console.log("json: " + text);
console.log(`size: ${Buffer.byteLength(text)} bytes, ${[...text].length} characters`);
// Pitfall 1: JSON numbers are often read as 64-bit floats (JavaScript always does).
const bigID = 9007199254740993n; // 2^53 + 1, as a BigInt so we can print it exactly
console.log(`id ${bigID} read as a float64: ${Number(bigID)}`);
// Pitfall 2: money in floats.
console.log("0.1 + 0.2 as float64:", String(0.1 + 0.2));
const cents = 10 + 20;
console.log(`10 + 20 as integer cents: ${cents} -> "${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}"`);// A JSON value: null, bool, integer, float, string, array, or object (with ordered keys).
enum Json {
Null,
Bool(bool),
Int(i64),
Float(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
// encode turns an in-memory value into JSON text, following the JSON rules by hand.
fn encode(v: &Json) -> String {
match v {
Json::Null => "null".into(),
Json::Bool(b) => b.to_string(),
Json::Int(n) => n.to_string(),
Json::Float(f) => f.to_string(),
Json::Str(s) => {
let mut out = String::from("\"");
for ch in s.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), // other control characters
c => out.push(c), // everything else, including Bangla, goes in as UTF-8
}
}
out + "\""
}
Json::Arr(items) => format!("[{}]", items.iter().map(encode).collect::<Vec<_>>().join(",")),
Json::Obj(pairs) => {
let parts: Vec<String> = pairs.iter().map(|(k, val)| encode(&Json::Str(k.clone())) + ":" + &encode(val)).collect();
format!("{{{}}}", parts.join(","))
}
}
}
fn main() {
use Json::*;
let s = |x: &str| Str(x.to_string());
let order = Obj(vec![
("id".into(), Int(42)),
("customer".into(), s("রহিম \"R\"")),
("items".into(), Arr(vec![Obj(vec![("sku".into(), s("pen")), ("qty".into(), Int(2)), ("price".into(), Float(12.5))])])),
("paid".into(), Bool(false)),
("coupon".into(), Null),
("note".into(), s("line1\nline2")),
]);
let text = encode(&order);
println!("json: {text}");
println!("size: {} bytes, {} characters", text.len(), text.chars().count());
// Pitfall 1: JSON numbers are often read as 64-bit floats (JavaScript always does).
let big_id: i64 = 9007199254740993; // 2^53 + 1
println!("id {big_id} read as a float64: {:.0}", big_id as f64);
// Pitfall 2: money in floats.
let (a, b) = (0.1_f64, 0.2_f64);
println!("0.1 + 0.2 as float64: {}", a + b);
let cents = 10 + 20;
println!("10 + 20 as integer cents: {cents} -> \"{}.{:02}\"", cents / 100, cents % 100);
}# A JSON value is one of: None, bool, int, float, str, list (array), or a list of (key, value) pairs (object).
class Obj(list):
"""An object: a list of (key, value) pairs, so key order is kept."""
def encode(v):
"""Turn an in-memory value into JSON text, following the JSON rules by hand."""
if v is None:
return "null"
if isinstance(v, bool): # check bool before int: in Python, True is an int
return "true" if v else "false"
if isinstance(v, (int, float)):
return repr(v)
if isinstance(v, str):
out = '"'
for ch in v:
if ch == '"':
out += '\\"'
elif ch == "\\":
out += "\\\\"
elif ch == "\n":
out += "\\n"
elif ord(ch) < 0x20: # other control characters
out += f"\\u{ord(ch):04x}"
else: # everything else, including Bangla, goes in as UTF-8
out += ch
return out + '"'
if isinstance(v, Obj):
return "{" + ",".join(encode(k) + ":" + encode(val) for k, val in v) + "}"
if isinstance(v, list):
return "[" + ",".join(encode(e) for e in v) + "]"
raise TypeError("not JSON")
order = Obj([
("id", 42),
("customer", 'রহিম "R"'),
("items", [Obj([("sku", "pen"), ("qty", 2), ("price", 12.5)])]),
("paid", False),
("coupon", None),
("note", "line1\nline2"),
])
text = encode(order)
print("json: " + text)
print(f"size: {len(text.encode())} bytes, {len(text)} characters")
# Pitfall 1: JSON numbers are often read as 64-bit floats (JavaScript always does).
big_id = 9007199254740993 # 2^53 + 1
print(f"id {big_id} read as a float64: {float(big_id):.0f}")
# Pitfall 2: money in floats.
print("0.1 + 0.2 as float64:", repr(0.1 + 0.2))
cents = 10 + 20
print(f'10 + 20 as integer cents: {cents} -> "{cents // 100}.{cents % 100:02d}"')import java.nio.charset.StandardCharsets;
import java.util.*;
public class Main {
// A JSON value is one of: null, Boolean, Long, Double, String, List (array), or Obj (object with ordered keys).
static class Obj extends LinkedHashMap<String, Object> {
Obj with(String k, Object v) { put(k, v); return this; }
}
// encode turns an in-memory value into JSON text, following the JSON rules by hand.
static String encode(Object v) {
if (v == null) return "null";
if (v instanceof Boolean || v instanceof Long || v instanceof Double) return v.toString();
if (v instanceof String s) {
StringBuilder out = new StringBuilder("\"");
s.codePoints().forEach(c -> {
if (c == '"') out.append("\\\"");
else if (c == '\\') out.append("\\\\");
else if (c == '\n') out.append("\\n");
else if (c < 0x20) out.append(String.format("\\u%04x", c)); // other control characters
else out.appendCodePoint(c); // everything else, including Bangla, goes in as UTF-8
});
return out.append('"').toString();
}
if (v instanceof List<?> list) {
StringJoiner j = new StringJoiner(",", "[", "]");
for (Object e : list) j.add(encode(e));
return j.toString();
}
if (v instanceof Obj o) {
StringJoiner j = new StringJoiner(",", "{", "}");
o.forEach((k, val) -> j.add(encode(k) + ":" + encode(val)));
return j.toString();
}
throw new IllegalArgumentException("not JSON");
}
public static void main(String[] args) {
Obj order = new Obj()
.with("id", 42L)
.with("customer", "রহিম \"R\"")
.with("items", List.of(new Obj().with("sku", "pen").with("qty", 2L).with("price", 12.5)))
.with("paid", false)
.with("coupon", null)
.with("note", "line1\nline2");
String text = encode(order);
System.out.println("json: " + text);
System.out.printf("size: %d bytes, %d characters%n", text.getBytes(StandardCharsets.UTF_8).length, text.codePointCount(0, text.length()));
// Pitfall 1: JSON numbers are often read as 64-bit floats (JavaScript always does).
long bigId = 9007199254740993L; // 2^53 + 1
System.out.printf("id %d read as a float64: %.0f%n", bigId, (double) bigId);
// Pitfall 2: money in floats.
double a = 0.1, b = 0.2;
System.out.println("0.1 + 0.2 as float64: " + (a + b));
int cents = 10 + 20;
System.out.printf("10 + 20 as integer cents: %d -> \"%d.%02d\"%n", cents, cents / 100, cents % 100);
}
}Output (the same in all five languages):
json: {"id":42,"customer":"রহিম \"R\"","items":[{"sku":"pen","qty":2,"price":12.5}],"paid":false,"coupon":null,"note":"line1\nline2"}
size: 135 bytes, 127 characters
id 9007199254740993 read as a float64: 9007199254740992
0.1 + 0.2 as float64: 0.30000000000000004
10 + 20 as integer cents: 30 -> "0.30"
Reading the output:
- The quote in
রহিম "R"became\"and the newline in the note became\n, so the text stays one valid string. The Bangla letters went in as UTF-8. - 135 bytes, 127 characters: the four Bangla characters take 3 bytes each, so 8 extra bytes.
Content-Lengthmust say 135. 9007199254740993became...992when stored as a 64-bit float. In JavaScript every JSON number is stored this way, so the ID silently changes.0.1 + 0.2is0.30000000000000004, but 10 + 20 paisa is exactly 30, formatted as"0.30"only at the end.
The same JSON text, read by two real parsers on this machine:
$ node -e 'console.log(JSON.parse("{\"id\": 9007199254740993}").id)'
9007199254740992
$ python3 -c 'import json; print(json.loads("{\"id\": 9007199254740993}")["id"])'
9007199254740993
$ python3 -c 'import json; print(json.dumps({"name": "রহিম"}), json.dumps({"name": "রহিম"}, ensure_ascii=False))'
{"name": "রহিম"} {"name": "রহিম"}
- Node rounds the ID, Python doesn't (Python integers have no size limit). Same bytes, different values. Your API has to work for the weakest reader.
- Python escapes Bangla by default (
র...), or writes UTF-8 withensure_ascii=False. Both are valid JSON for the same string; the escaped one is just longer.
Real engineering
- Define response types explicitly. A DTO or serializer per endpoint decides exactly which fields go out. Never serialize ORM models directly.
- Validate input at the boundary. Parse into a typed structure and reject unknown types, missing required fields and out-of-range values with 400/422 (lesson 5). Libraries: JSON Schema, pydantic, zod, Go struct tags plus a validator.
- Pick conventions once, for the whole API:
snake_caseorcamelCase, IDs as strings, money as integer minor units, timestamps as ISO 8601 UTC,nullvs missing field meaning. Write them down. - Limit size and depth. A 500 MB body or an array nested 100,000 levels deep can exhaust memory or crash a parser. Set body limits and nesting limits.
- Compress large responses (gzip/brotli, lesson 6). JSON's repeated key names compress very well.
- Consider binary formats internally. Between your own services, protobuf with gRPC gives smaller messages and a shared schema. Keep JSON for public and browser-facing APIs.
When it breaks
Pick a failure
API id 1795139962000123457, link /orders/1795139962000123456
Think before you read on
Your API has "discount": null in some responses and no discount key at all in others. A client sends PATCH /orders/7 with {"discount": null}. Should that mean "remove the discount" or "don't touch the discount"? Why does JSON make this question unavoidable?
Reveal
JSON has two different ways to say "nothing": a key with null, and a missing key. In a PATCH (lesson 4), these naturally mean different things: missing = leave it alone, null = set it to empty. Many languages blur them when decoding (a missing field and a null both become None or nil), so the server can't tell which the client meant. Decide the rule for your API, document it, and use decoding that keeps the difference (optional-of-optional types, or checking whether the key was present) for PATCH bodies.
Check yourself
1. What are the six kinds of value JSON can represent?
Answer
null, booleans, numbers, strings, arrays and objects.
2. Why should large integer IDs be sent as JSON strings?
Answer
Many parsers, including every JavaScript one, store JSON numbers as 64-bit floats, which are exact only up to 2^53. Larger integers get silently rounded; strings arrive exactly.
3. How should money be represented in JSON, and why not as a float?
Answer
As integer minor units (paisa, cents) or a decimal string, with the currency. Binary floats can't represent most decimal fractions exactly, so sums drift (0.1 + 0.2 = 0.30000000000000004).
4. Why shouldn't you serialize database models directly into API responses?
Answer
They often contain fields that must never leave the server (password hashes, internal flags), and any new column would automatically become part of your public API. An explicit response type controls exactly what goes out.
Your challenge: write the decoder
Write the other half: a JSON parser for the same subset.
- Read one value at a time:
null,true,false, a number, a string (handling\",\\,\nand\uXXXX), an array or an object. Skip whitespace between tokens. - Keep integers and floats apart: digits with no
.orebecome an integer (as a big-enough type, or a string if too big). - Parse the
json:line your encoder printed, then encode the result again.
Before you run it, predict whether the re-encoded text will be byte-for-byte identical to the original.
You've succeeded when encoding → parsing → encoding gives exactly the same 135 bytes, "id":9007199254740993 survives your parser unchanged, and malformed input like {"a":1,} is rejected with an error instead of crashing.
The mental model
Serialization describes in-memory values as bytes in a shared format, and deserialization rebuilds them in the reader's own types. JSON has only six kinds of value, so it's readable everywhere, but numbers have no size (big IDs and money get rounded as floats), dates and money have no type, and null differs from missing. Choose explicit shapes and conventions for the weakest reader, escape and count bytes correctly, and validate everything that comes in.
Station stamp
Finish the chapter
Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.
Go Pro to earn XP →