Computing Foundations › APIs and the Web › Day 24

Day 24: JSON and Data Serialization

Day 24 of 365 — JSON and Data Serialization

After this lesson you will be able to read and write JSON confidently — its six value types, its syntax rules, and its common pitfalls — turn data into a string and back through serialization, and choose JSON or a rival format for any data-exchange job.

Course
Computing Foundations
Category
APIs and the Web
Reading time
≈ 40 min
Practical time
≈ 30 min
Lesson duration
1h 10m
Last verified
2026-07-12

Hands-on lab for this lesson

Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/computing-foundations/day-024-json-and-data-serialization

  1. Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
    git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git
    cd ai-roadmap-365.github.io
  2. Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
    cd labs/sections/computing-foundations/day-024-json-and-data-serialization
  3. Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
  4. Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
    bash tests/run_tests.sh   # or the test command named in the lab README

You can also open the lab as a local page (works offline, shows the file tree and expected output).

Learning objectives

By the end of this lesson you will be able to:

Prerequisites

Why this matters


The idea in plain language

Diagram: how a value travels between two programs as text


Historical background

Diagram: XML compared with JSON


What it is — and what it is not

It is:

It is not:


Why it was created and what problems it solves


How it works

The six value types

TypeExampleNotes
Object{"lat": 26.9, "lon": 75.8}Unordered "key": value pairs; keys are double-quoted strings
Array["temp", "humidity"]Ordered list of any values; position matters
String"Nimbus-7"Double-quoted, Unicode throughout, backslash escapes
Number512, 26.9124, -4e3One numeric type; no quotes, no leading +
Booleantrue, falseExactly these two lowercase words, unquoted
NullnullLowercase; a deliberately empty value

Diagram: an annotated JSON object showing the six value types nested inside one another

The syntax rules that matter

Serializing and parsing

Diagram: the serialization round trip from an in-memory object to a JSON string, across a channel, and back to an object

The pitfalls, concretely

Diagram: the six most common JSON errors

Schema validation at a glance

Diagram: syntactic validity compared with schema validation


An everyday analogy

Diagram: why comments were removed from JSON and what to use instead

Flat-pack furniture.

The furnitureSerialization
The assembled chairA value in memory
Taking it apart into labelled piecesSerializing
The flat boxThe JSON string
Shipping the boxThe network or the file
Rebuilding from the piecesParsing
The instruction sheet’s expectationsA schema

Examples in practice

Diagram: how to interpret a JSON parse error message


Implications: security, privacy, performance, scalability, and cost

Diagram: parsing JSON compared with evaluating it as code


Alternatives: free, open source, and commercial

Diagram: a single JSON array compared with JSON Lines

FormatTypeWhere it fits
JSONFree, universalAPIs, configuration, small to medium data
JSONLFree, conventionOne object per line; streaming and training data
YAMLFree, open sourceConfiguration humans write; a superset of JSON, with traps
TOMLFree, open sourceConfiguration, with fewer traps than YAML
CSVFree, universalFlat tabular data, and nothing nested
ParquetFree, open sourceColumnar, compressed, for large analytical datasets
Protocol BuffersFree, open sourceCompact binary with a schema, for service-to-service

TermWhat it actually is
SerializationTurning a value into text or bytes
ParsingTurning it back into a value
JSONOne text format for doing so
JSONLOne JSON document per line
SchemaA description of what shape a document must have
ValidationChecking a document against a schema
EncodingBytes to characters, from Day 5 — a different layer entirely

When to use it — and when not to

Diagram: which serialization format suits which data size


The AI connection

Diagram: the steps to obtain and validate structured output from a model


Knowledge check

quiz:
  question: "A service sends account identifiers as JSON strings rather than numbers, even though every identifier is numeric. What problem does that avoid?"
  options:
    - "JSON numbers are typically read as floats, so integers beyond about 2^53 lose precision"
    - "JSON numbers cannot begin with a zero, which some identifiers require"
    - "String comparison is faster than numeric comparison in most parsers"
    - "JSON has no integer type at all, so numeric values are rejected by strict parsers"
  answer_index: 0
  explanation: "JSON has one numeric type, and most parsers read it into a double-precision float, which represents integers exactly only up to 2^53. A nineteen-digit identifier silently loses its final digits, so services that care send them as strings deliberately."

Hands-on exercise

Round-trip real data, then break it in each of the documented ways. Worked through fully in the Day 24 lab directory.

What you are doingCommand
Pretty-print a responsecurl -s URL | python3 -m json.tool
Query it with jqcurl -s URL | jq '.items[0].name'
Validate a filepython3 -c "import json,sys; json.load(open(sys.argv[1]))" f.json
Round-trip in Pythonjson.loads(json.dumps(obj)) == obj
Break it: trailing commaAdd one and re-run the validator
Break it: big integerjson.loads('{"id": 12345678901234567890}')
Read JSONL line by linewhile read -r l; do echo "$l" | jq -r .id; done < data.jsonl

Expected output

{
    "id": 1,
    "title": "delectus aut autem"
}
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 3 column 5
12345678901234567168

Validate your work

Troubleshooting

Common mistakes


Practice assignment


Extension challenge


Quiz

Q1. What does it mean to serialize a piece of data?

  1. To sort the data into ascending order before saving it
  2. To turn an in-memory value into a string that can be rebuilt
  3. To encrypt the data so it cannot be read on the network
  4. To compress the data into the smallest possible binary form on disk
Show answer

Answer: B. To turn an in-memory value into a string that can be rebuilt

Serialization writes a living in-memory value out as a self-contained string of characters; parsing reads that string back into an equivalent value. Sorting, encryption, and compression are separate concerns.

Q2. Which of the following is NOT one of JSON's six value types?

  1. object
  2. array
  3. date
  4. null
Show answer

Answer: C. date

JSON has exactly six value types: object, array, string, number, boolean, and null. There is no native date type — dates must be encoded as strings or numbers by convention.

Q3. Why is `{"name": "x",}` invalid JSON?

  1. Keys are not allowed to be strings
  2. The value "x" must be a number rather than a quoted string
  3. Objects must contain at least two keys
  4. It has a trailing comma after the last key-value pair
Show answer

Answer: D. It has a trailing comma after the last key-value pair

The comma after the last pair is a trailing comma: it promises another key-value pair that never arrives, so the parser stops and reports an error. Trailing commas are one of the most common JSON mistakes.

Q4. What is the difference between the JSON values `512` and `"512"`?

  1. `512` is a number and `"512"` is a string, and services treat them as different types
  2. They are identical; quotes around numbers are optional in JSON
  3. `"512"` is valid but `512` is not, because all JSON values must be quoted
  4. `512` is an integer type and `"512"` is a floating-point type
Show answer

Answer: A. `512` is a number and `"512"` is a string, and services treat them as different types

JSON distinguishes strictly between a number (`512`) and a string of digits (`"512"`). A service expecting one will reject or misread the other, so the distinction matters in every request you send.

Q5. Who specified JSON and published its grammar, and where did the syntax originate?

  1. Tim Berners-Lee, from the syntax of HTML
  2. Douglas Crockford, from JavaScript's object and array notation
  3. A W3C committee, from the syntax of XML
  4. Google, from the Protocol Buffers schema language
Show answer

Answer: B. Douglas Crockford, from JavaScript's object and array notation

Douglas Crockford specified JSON in the early 2000s and published its grammar at json.org, drawing the syntax from JavaScript's object literal notation — though JSON itself is language-independent text.

Q6. What is the purpose of JSON Schema?

  1. To compress JSON documents into a compact binary format for storage
  2. To encrypt the values inside a JSON document
  3. To describe the shape a valid JSON document must have
  4. To translate JSON automatically into XML
Show answer

Answer: C. To describe the shape a valid JSON document must have

A JSON document is valid JSON regardless of whether it makes sense for your purpose. JSON Schema is a separate JSON document that specifies the required structure, so a validator can report exactly where data violates the rules.

Q7. When would a binary format such as Protocol Buffers or MessagePack be a better choice than JSON?

  1. Whenever a human might need to read the data by eye
  2. For configuration files that people edit by hand
  3. Whenever the data contains nested objects and arrays
  4. For high-volume internal traffic where size or speed really matters
Show answer

Answer: D. For high-volume internal traffic where size or speed really matters

Binary formats trade human-readability for compactness and speed, which pays off at high volume between internal services once profiling shows serialization is the bottleneck. For readable, universal exchange, JSON remains the default.

Q8. Why should you always parse untrusted JSON with a real parser rather than evaluating it as code?

  1. Evaluating a malicious payload could run arbitrary code
  2. A parser produces prettier formatted output
  3. Evaluating it is slower than parsing the text
  4. Parsers automatically encrypt the result
Show answer

Answer: A. Evaluating a malicious payload could run arbitrary code

Because JSON's syntax overlaps with JavaScript, evaluating a JSON string as code is tempting but dangerous: a malicious payload could execute. A real parser treats the input strictly as data and can only produce the six JSON value types.

Glossary

serialization
The act of turning an in-memory value into a flat, self-contained string of characters that can be stored or transmitted and later rebuilt.
parsing
The reverse of serialization: reading a string and reconstructing an equivalent in-memory value from it. Also called deserializing.
JSON
JavaScript Object Notation — a compact, human-readable text format for representing structured data, and the dominant format for web data exchange.
object
A JSON value that is an unordered collection of "key": value pairs, where every key is a double-quoted string; it maps to a dictionary or map in most languages.
array
A JSON value that is an ordered list of values of any type, written inside square brackets; it maps to a list in most languages.
key-value pair
A single entry inside a JSON object: a double-quoted key, a colon, and a value, such as "lat": 26.9124.
null
The JSON literal for a value that is deliberately empty — a present slot whose contents are intentionally nothing.
schema
A description of the shape valid data must take; for JSON, JSON Schema is itself a JSON document specifying required keys, value types, and allowed ranges.
round-trip property
The contract that parsing a value you just serialized returns a value equal to the original, so no information is lost in the trip out and back.
XML
The Extensible Markup Language, a tag-based text format for structured data that predates JSON and suits document-style and legacy enterprise data.
YAML
A text data format that uses indentation instead of braces, favored for configuration files that people edit by hand.
CSV
Comma-separated values, a flat text format for tables of uniform rows; simple and spreadsheet-friendly but unable to express nesting.
MessagePack
A binary serialization format that keeps JSON's exact data model in a smaller, faster encoding, used when compactness or speed matters more than readability.
Protocol Buffers
A schema-first binary serialization format from Google, designed for compact, fast data exchange between high-volume internal services.

Sources and further reading


Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.