Nested data

Part of the free LogicWiz Data Engineering course, Module 3: Python for data wrangling. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 11:15 on Thursday. Dana's app team sends every tap in the app as JSON Lines: 40 GB a day. Tess wants two plain tables out of it. Your first flattener dies on the very first line with KeyError: 'items'. Your second one runs, then asks for about 300 GB of memory to hold one 40 GB day. Nora: "The crash is one missing key. For the memory, weigh a single event."

You'll learn to

  • Turn objects into columns and lists into child rows
  • Tell a missing key from a null, and handle both
  • Flatten any depth with a function that calls itself
  • Work out what `json.loads` costs in memory and time

Learn

Open one event

Start by looking at what Dana's team sends. Every tap in the app is one event: one line of JSON in a file, one file per day.

A flat record would be a row of plain values. These are not flat. An event carries a small object that describes the phone, and sometimes a list of the products it touched. Run the card and find both in the output: curly braces {} are an object, square brackets [] are a list.

Look at one event

import json

with open("landing/events/2025-06-01.jsonl") as f:
    events = [json.loads(line) for line in f if line.strip()]

print(len(events), "events")
print(json.dumps(events[1], indent=2))

67 events on 1 June, and this is the second. Find the object (device) and the list (items). Each one needs one of the two moves that come next.

Two moves turn nested data into tables

Tess's tools want tables: rows and columns, one value in each cell. Apps think in objects. Getting from one to the other takes only two moves.

Move one: an object inside a record becomes extra columns. device.os becomes a column called device_os.

Move two: a list inside a record becomes rows in a second table, a child table. Each row carries the parent's key, here event_id, so the two tables can be joined back together.

The rest of the lesson is about doing those two moves without crashing, without losing rows, and without running out of memory.

One event becomes two tables

A nested event with a device object and an items list is flattened in steps: the object becomes two columns in the events table, the list becomes a row in the event_items table, and an event with three items adds three child rows.

  1. The event as it arrives. One record with two nested parts: an object, device, and a list, items. Both tables are still empty.

  2. Move one: the object becomes columns. device.os turns into the column device_os, and device.app_version into device_app_version. Still one row for one event.

  3. Move two: the list becomes rows. The item gets its own row in a second table, and takes the parent's event_id with it so the two tables can be joined back.

  4. Two more events. A purchase with three products adds one row to events and three to event_items. A page view adds one row to events and none to event_items.

The first box is the nested input. The other two are the tables Tess gets. Count the rows in each as you step.

Event e0042, before and after

Where it goesWhat it looks like
Input (nested){"eventid": "e0042", "userid": null, "type": "addtocart", "device": {"os": "ios", "appversion": "5.2.1"}, "items": [{"productid": 114, "qty": 1}]}
events: one row per eventeventid=e0042, userid=None, type=addtocart, deviceos=ios, deviceappversion=5.2.1
eventitems: one row per itemeventid=e0042, productid=114, qty=1

The object became two columns. The list became a row in its own table, and event_id travels with it. An event with three items gives three child rows; an event with no items gives none.

The crash on line one: a missing key

Now the first crash. The first event in the file is a page view, and a page view has no items key at all. e["items"] raises KeyError, and one such event stops the whole load.

In JSON a value can be missing in two different ways. The key can be absent: no items. Or the key can be there, holding null: an anonymous visitor has "user_id": null, which Python reads as None.

e.get("items", []) handles the first case: it returns the default when the key is absent. It does nothing for the second. e.get("user_id", "anonymous") still returns None, because the key exists. To replace a null you have to test for it: if uid is None.

Move one: flatten one level

import json

def flatten_event(e):
    device = e.get("device") or {}
    return {
        "event_id": e["event_id"],
        "user_id": e.get("user_id"),
        "type": e["type"],
        "ts": e["ts"],
        "device_os": device.get("os"),
        "device_app_version": device.get("app_version"),
    }

with open("landing/events/2025-06-01.jsonl") as f:
    events = [json.loads(line) for line in f if line.strip()]

flat = [flatten_event(e) for e in events]
print(len(flat), "rows")
for row in flat[:2]:
    print(row)

e.get("device") or {} covers both cases at once: an absent device and "device": null each become an empty dict, so the next two .get calls are always safe. event_id uses square brackets on purpose: an event without an id is broken, and failing loudly is right.

Remember: .get(key, default) covers a missing key. It does not cover a null. For an object that may be either, write e.get("device") or {}.

A list becomes rows, not columns

Move two. A list cannot become columns: one event has one item, another has five. Columns named items_0, items_1 break the day an event has more items than you planned for.

So each element gets its own row in the child table, with the parent's key copied in. In Python that is a loop inside a loop. Spark calls it explode; SQL engines call it UNNEST or FLATTEN.

Watch the row counts. The child table has one row per element, so it is usually longer than the parent table. An event with an empty list, or with no list at all, adds nothing. After every flatten, count both tables and check that the numbers make sense.

Move two: explode items into child rows

import json

def explode_items(events):
    rows = []
    for e in events:
        for item in e.get("items", []):
            rows.append({"event_id": e["event_id"], "product_id": item["product_id"], "qty": item.get("qty", 1)})
    return rows

with open("samples/checkout.jsonl") as f:
    sample = [json.loads(line) for line in f if line.strip()]
items = explode_items(sample)
print(len(sample), "events ->", len(items), "item rows")
for row in items:
    print(row)

with open("landing/events/2025-06-01.jsonl") as f:
    day = [json.loads(line) for line in f if line.strip()]
print(len(day), "events on 1 June ->", len(explode_items(day)), "item rows")

The sample first: two events became three item rows. The purchase fans out, the page view adds nothing. Then the real 1 June file: there every event with items has exactly one, so 67 events give 43 item rows.

Exploding two lists at once multiplies rows. If an order has 3 items and 2 coupons and you loop over both together, you get 3 × 2 = 6 rows, and every item's quantity is now counted twice. Give each list its own child table, keyed by the parent. And do not let .get defaults hide real problems: a missing event_id should fail, not quietly become None.

Deeper nesting: a function that calls itself

Real records nest more than one level: {"device": {"os": "ios", "screen": {"w": 390, "h": 844}}}. Writing every path by hand gets old fast. So a favourite interview task is a general flatten that works at any depth.

The idea: walk through the dict. When a value is a plain value, keep it. When a value is itself a dict, go inside it, and carry the name of the key you came through as a prefix. A function that calls itself like this is called recursive.

Lists are left alone on purpose. They belong in child tables.

The prefix grows on the way down

A tree of one nested event: event_id is a plain value, device is a dict holding os and a screen dict with w and h, and items is a list; each plain value shows the flat column name it becomes.

Read it top to bottom. At each amber node the function calls itself and the prefix grows by one name. The name on the right of each green node is the column it becomes.

A recursive flatten

def flatten(d, prefix=""):
    out = {}
    for key, value in d.items():
        name = f"{prefix}_{key}" if prefix else key
        if isinstance(value, dict):
            out.update(flatten(value, name))
        else:
            out[name] = value
    return out

e = {"event_id": "e7", "device": {"os": "ios", "screen": {"w": 390, "h": 844}}, "items": [{"product_id": 101}]}
print(flatten(e))

The output has exactly the green names from the picture, plus items, untouched. Passing name down is what keeps device_screen_w from clashing with some other w.

Where the 300 GB went

The flattener works now. But it asked for 300 GB of memory to hold a 40 GB day. Nora's advice: weigh one event.

On disk, one event is a line of text: 151 bytes. json.loads turns that text into Python objects. A dict for each JSON object. A string for every key and every text value. A number for each number. Building all those objects is the expensive part, and each of them carries its own overhead on top of the data it holds.

One 151-byte event, parsed (64-bit CPython 3.12)

Two bars on one scale: the 151-byte JSON line on disk, and the 1,130 bytes of Python objects it becomes, split into the two dicts, the key strings and the value strings.

Both bars are on one scale: the short grey one is the text on disk, the long one is the same event in memory, measured with sys.getsizeof on each object. user_id: null costs nothing extra, because every None is the same object. The red blocks are key names, and every event carries its own copies.

Every line pays for its keys again

Look at the red blocks once more: the key names. "event_id" is the same eight letters in every event, yet each event holds its own copy, 49 bytes a time.

Inside one json.loads call the decoder is smarter. It keeps a note of every key it has seen, called a memo, and reuses the same string the second time. But each line of a JSON Lines file is a separate call, so the memo starts empty every time.

Three fixes, cheapest first. Keep only the fields you need, as tuples, as soon as a record is parsed. Pass the keys through sys.intern(), so each name exists once. Or let DuckDB's read_json_auto or Spark read the JSON straight into typed columns, and never build a dict per record.

The 192 events of data/events.jsonl, in memory

Bars compare the 31.9 KB file with the Python objects it becomes: 177.2 KB parsed as one array, 205.8 KB as JSON Lines with top-level keys interned, and 263.8 KB as plain JSON Lines.

Measured on 64-bit CPython 3.12 by walking every object once. The grey bar is the file. Red is plain JSON Lines. Green is the same records parsed as one array, where the memo shares the keys. Interning only the top-level keys (amber) gets most of the way; the nested device and items keys are the rest.

Shared keys, measured in this browser

import json, sys

lines = [l for l in open("data/events.jsonl") if l.strip()]
a, b = json.loads(lines[0]), json.loads(lines[1])
doc = json.loads("[" + ",".join(lines) + "]")
print("keys shared across lines:", next(iter(a)) is next(iter(b)))
print("keys shared in one document:", next(iter(doc[0])) is next(iter(doc[1])))

def deep(o, seen):
    # bytes of o and everything it holds, counting each object once
    if id(o) in seen:
        return 0
    seen.add(id(o))
    n = sys.getsizeof(o)
    if isinstance(o, dict):
        n += sum(deep(k, seen) + deep(v, seen) for k, v in o.items())
    elif isinstance(o, list):
        n += sum(deep(x, seen) for x in o)
    return n

print("text bytes:", sum(len(l.encode()) for l in lines))
print("JSON Lines objects:", deep([json.loads(l) for l in lines], set()))
print("one array objects:", deep(doc, set()))

The first two lines show the memo at work: keys are shared inside one document, not across lines. This browser runs 32-bit WebAssembly, so every object is smaller than on a 64-bit server (Lesson 3.7 has the table). The ratios are the point: about 4.8 times the text as JSON Lines here, 3.2 times as one document.

Numbers to remember

WhatNumberGood to know
One event on disk151 bytesas Python objects: 1,130 bytes, 7.5 times the text
A 40 GB day as Python dictsabout 300 GB40 GB × 7.5
A str on 64-bit CPython 3.1241 bytes of overheadplus 1 byte per ASCII character: "eventid" is 49 bytes
192 events, 31.9 KB of text263.8 KB as JSON Lines177.2 KB as one array; 205.8 KB with top-level keys interned
Splitting text into linesabout 400 MB/sone laptop core, CPython 3.12, SwiftKart-shaped events
json.loads, one call per lineabout 55 MB/sas one array: about 115 MB/s (fewer calls, shared keys)
Parsing a 40 GB day40,000 MB ÷ 55 MB/s = about 730 seconds12 minutes of one core before your own code runs

The speeds move with the shape of the records, so measure your own data before you size a job. Streaming (Lesson 3.4) limits how many records exist at once; it does not make each one smaller. And every tool has the two moves: pandas has json_normalize, Spark has explode and dotted names (device.os), Snowflake has LATERAL FLATTEN, BigQuery and Postgres have UNNEST. Ingestion tools such as dlt and Airbyte do it for you: dlt names the child table events__items.

What changed at SwiftKart

By the end of Thursday, Tess has her two tables: events, one row per event, and event_items, one row per item, joined on event_id. The loader counts both after every run.

The 300 GB is gone too. The new flattener keeps only the six fields the tables need and lets go of each parsed dict straight away. For the big daily file it hands the JSON to DuckDB, which reads it directly into columns.

Flat tables make one more thing visible. The same order shows up in several daily files. The next lesson deals with that: removing duplicates, grouping and joining by hand, with nothing but a dict.

In one line

An object becomes columns and a list becomes child rows that carry the parent's key; .get covers a missing key but not a null; and a parsed event weighs about 7.5 times its text.

Interview corner

Your JSON Lines flattener runs out of memory on a 40 GB day. Walk me through the numbers and the fix.

Parsed into dicts, each event costs several times its text: on 64-bit CPython a 151-byte event became 1,130 bytes, so 40 GB of text is roughly 300 GB of objects, and every record carries its own copies of the key strings because each line is a separate json.loads call. First I would stream (one record or one batch at a time) so memory no longer grows with the file. Then I would shrink what I keep: project to the needed fields as tuples or typed columns, intern repeated keys, or let DuckDB or Spark parse JSON straight into columns. Parsing is also CPU-bound at roughly 55 MB/s per core, so a 40 GB day needs about 12 core-minutes just to parse, which sizes the job.

How would you flatten a deeply nested JSON record in Python?

Recursively: walk the dict, and when a value is a dict, call the same function with the key added to a prefix; otherwise store the value under the joined name, such as device_screen_w. Lists are not spread into numbered columns: they become child tables with one row per element and the parent key copied in. I would also decide up front how missing keys and nulls are handled.

What is the difference between a missing key and a null value, and why does it matter?

A missing key means the producer did not send the field; a null means it sent the field with no value. .get(key, default) only covers the first case. They can mean different things, an older app version that does not know the field versus a user who is anonymous, so a good pipeline either keeps the difference or decides on purpose to treat them the same.

You explode an array and revenue doubles. What happened?

Exploding repeats the parent row once per element. If a parent-level value such as the order total stays on every child row and is then summed, it is counted once per element. Sum parent-level measures at the parent grain, or sum the child-level measure (the line amounts) instead. Exploding two arrays in one go multiplies the rows again.