Part 03 · The Language of the Web

JSON and Serialization

JSONSerialization

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 memoryWhy it can't just be sent
Pointers / referencesAn address like 0xc000012080 means nothing in another process
Language typesA Go struct, a Python dict, a Java record look nothing alike in memory
Number layouts32/64-bit, big/little endian, int vs float vary between languages and machines
StringsUTF-8 in Go and Rust, UTF-16 inside JavaScript and Java
Dates, money, enumsEvery 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.

only bytes can cross a wireGo structmemory addressesPython dictits own layout{"id":42}serialize: object → bytes7b 22 69 64 22 3a 34 32 7ddeserialize: bytes → object
An object in a Go program is flattened into bytes: field names and values written out as text. The bytes cross the wire, and a Python program reads them and builds its own object with the same fields. Neither side ever sees the other's memory, only the agreed format.

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

  1. 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.
  2. 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.
  3. Numbers have no size or type in the spec. 42, 12.5 and 9007199254740993 are 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.
  4. Floats can't hold most decimals exactly. 0.1 + 0.2 is 0.30000000000000004. Money should travel as integer minor units ("amount_paisa": 1250) or as a decimal string ("12.50"), never as a float.
  5. 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.
  6. Object key order isn't guaranteed, and duplicate keys are undefined behaviour. Don't rely on either.
  7. 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.
  8. 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.
Predict first

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

Step through it

Serialize, send, deserialize

Go structJSON bytesNetworkJS object

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?

Try each case

Safe JSON or a trap?

{"id": 1795139962000123456}
breaks: Over 2^53, so JavaScript (and some other parsers) will round it. Send IDs as strings.

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)
}

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-Length must say 135.
  • 9007199254740993 became ...992 when stored as a 64-bit float. In JavaScript every JSON number is stored this way, so the ID silently changes.
  • 0.1 + 0.2 is 0.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 with ensure_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_case or camelCase, IDs as strings, money as integer minor units, timestamps as ISO 8601 UTC, null vs 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

Try each case

Pick a failure

API id 1795139962000123457, link /orders/1795139962000123456
breaks: The JS client rounded a large numeric ID. Send IDs as strings.

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 \", \\, \n and \uXXXX), an array or an object. Skip whitespace between tokens.
  • Keep integers and floats apart: digits with no . or e become 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 →