TExcelTAD

JSON and JSON Lines

JSON (JavaScript Object Notation) is the language of web APIs, configuration files and annotation formats. Unlike CSV it has types (strings, numbers, booleans, null) and nesting: objects inside objects, lists inside objects. That makes it a natural fit for records that do not fit a flat table, such as an order with a list of items or an image with a list of boxes. JSON Lines (JSONL, also NDJSON) puts one JSON object per line, which is how logs, event streams and many ML datasets (for example fine-tuning data for language models) are stored. The JSON course covers the syntax; this lesson is about JSON as a data source for ML.

A JSON document vs JSON Lines

python · try it yourself
import json

orders = [
    {"order_id": 1, "customer": {"id": "C7", "country": "VN"}, "items": [{"sku": "A1", "qty": 2}, {"sku": "B4", "qty": 1}], "paid": True},
    {"order_id": 2, "customer": {"id": "C9", "country": "DE"}, "items": [{"sku": "A1", "qty": 1}], "paid": False},
]

doc = json.dumps(orders)                               # one document: a list
jsonl = "\n".join(json.dumps(o) for o in orders)       # one object per line
print(doc[:70], "...")
print()
print(jsonl)
print()
first = json.loads(jsonl.splitlines()[0])              # each line parses on its own
print("first order has", len(first["items"]), "items, paid:", first["paid"])
[{"order_id": 1, "customer": {"id": "C7", "country": "VN"}, "items": [ ...

{"order_id": 1, "customer": {"id": "C7", "country": "VN"}, "items": [{"sku": "A1", "qty": 2}, {"sku": "B4", "qty": 1}], "paid": true}
{"order_id": 2, "customer": {"id": "C9", "country": "DE"}, "items": [{"sku": "A1", "qty": 1}], "paid": false}

first order has 2 items, paid: True

The difference matters for big data. A JSON document must be read completely before it can be parsed; a JSONL file can be streamed line by line, appended to without rewriting, and split across machines at line boundaries. A broken line damages one record, not the whole file.

Flattening nested records

Models want a flat table. pd.json_normalize turns nested objects into dotted column names, and with record_path it expands a list into one row per element:

python · try it yourself
import pandas as pd

orders = [
    {"order_id": 1, "customer": {"id": "C7", "country": "VN"}, "items": [{"sku": "A1", "qty": 2}, {"sku": "B4", "qty": 1}], "paid": True},
    {"order_id": 2, "customer": {"id": "C9", "country": "DE"}, "items": [{"sku": "A1", "qty": 1}], "paid": False},
]

per_order = pd.json_normalize(orders)
print(per_order.drop(columns="items"))
print()
per_item = pd.json_normalize(orders, record_path="items", meta=["order_id", ["customer", "country"]])
print(per_item)
print()
summary = per_item.groupby("order_id")["qty"].sum().rename("total_qty")
print(per_order[["order_id", "paid"]].join(summary, on="order_id"))
   order_id   paid customer.id customer.country
0         1   True          C7               VN
1         2  False          C9               DE

  sku  qty order_id customer.country
0  A1    2        1               VN
1  B4    1        1               VN
2  A1    1        2               DE

   order_id   paid  total_qty
0         1   True          3
1         2  False          1

Choosing the grain of the table (one row per order or one row per item) is a modelling decision: predicting whether an order is paid needs one row per order, so the item list must be summarised (count, total quantity) rather than exploded.

Reading JSON Lines with pandas

python · try it yourself
import io
import pandas as pd

log = """{"ts": "2026-06-01T09:00:00Z", "user": "u1", "event": "view", "ms": 120}
{"ts": "2026-06-01T09:00:04Z", "user": "u2", "event": "click", "ms": 85}
{"ts": "2026-06-01T09:00:09Z", "user": "u1", "event": "buy", "ms": null, "coupon": "SUMMER"}
"""
events = pd.read_json(io.StringIO(log), lines=True)
print(events)
events["ts"] = pd.to_datetime(events["ts"], utc=True)
print(events.dtypes.to_dict())
                     ts user  event     ms  coupon
0  2026-06-01T09:00:00Z   u1   view  120.0     NaN
1  2026-06-01T09:00:04Z   u2  click   85.0     NaN
2  2026-06-01T09:00:09Z   u1    buy    NaN  SUMMER
{'ts': datetime64[ns, UTC], 'user': dtype('O'), 'event': dtype('O'), 'ms': dtype('float64'), 'coupon': dtype('O')}

Two things to notice. Records do not need the same keys: only the last event has coupon, so the other rows get NaN (or None). That flexibility is useful, but it also means typos ("cupon") silently create new columns. And ts arrives as plain strings: JSON has no date type, so the code parses it explicitly, with utc=True because the Z at the end means UTC.

Validating structure

Because JSON has no fixed schema, check the structure before you trust it. Libraries such as jsonschema or Pydantic do this formally; the core idea fits in a few lines:

python · try it yourself
import json

schema = {"user": str, "event": str, "ms": (int, type(None))}
lines = [
    '{"user": "u1", "event": "view", "ms": 120}',
    '{"user": "u2", "event": "click", "ms": "85"}',
    '{"user": "u3", "ms": 40}',
    '{"user": "u4", "event": "view", "ms": 12',
]
for n, line in enumerate(lines, 1):
    try:
        rec = json.loads(line)
    except json.JSONDecodeError as e:
        print(f"line {n}: not valid JSON ({e.msg})")
        continue
    problems = [f"missing {k}" for k in schema if k not in rec]
    problems += [f"{k} has type {type(rec[k]).__name__}" for k, t in schema.items()
                 if k in rec and not isinstance(rec[k], t)]
    print(f"line {n}:", "ok" if not problems else ", ".join(problems))
line 1: ok
line 2: ms has type str
line 3: missing event
line 4: not valid JSON (Expecting ',' delimiter)

Pitfalls

  • Numbers as strings: "85" is a string. APIs that mix both make one column object.
  • Large integers: JSON numbers are often read as 64-bit floats in other languages (JavaScript), which lose precision beyond 2 to the power 53. Long ids should be strings.
  • Dates have no JSON type: agree on ISO 8601 strings with a time zone (2026-06-01T09:00:00Z).
  • null vs missing key vs empty string: three different things that often mean the same. Decide and document.
  • Pretty-printed JSONL is not JSONL: one object must be exactly one line.

Practice

  1. A file of 20 GB contains one JSON array of chat messages. Why is it hard to use, and what would you convert it to?
Answer

A single JSON array must be parsed as a whole, which needs more than 20 GB of memory and cannot be split or appended to. Convert it once (with a streaming parser) to JSON Lines, one message per line, or to Parquet for analysis.

  1. In the json_normalize example, what would per_item look like if an order had an empty items list?
Answer

That order would produce no rows at all in per_item: record_path creates one row per element, and an empty list has none. Joining back to per_order would give it a missing total, which you would fill with 0.

Test yourself

What is the main practical advantage of JSON Lines over one big JSON array?

  1. It is smaller
  2. Each line is a complete record, so files can be streamed, appended and split
  3. It supports more data types
  4. It needs no quotes

What does pd.json_normalize(orders, record_path="items") produce?

  1. One row per order
  2. One row per item in every order's list
  3. A single row
  4. A nested DataFrame

Two JSONL records use the keys coupon and cupon. After read_json(..., lines=True) you get…

  1. An error
  2. One coupon column
  3. Two separate, mostly empty columns
  4. The second record is dropped