Sub topic 13
When json_normalize is not the right tool
This chapter assumes you have used pd.json_normalize with record_path and meta, and that you know what explode does in general. It helps you spot cases where json_normalize is the wrong choice, and it shows what to use instead.
What json_normalize does not do well
json_normalize builds a flat table from a Python object that is already in memory. That design has limits:
- It cannot expand more than one list at a time into rows.
record_pathfollows a single path. - It leaves lists as Python lists in cells when you did not name them in
record_path. - It needs the whole document as dicts and lists, so memory use is a multiple of the file size.
- It does extra work when you only need two or three fields.
Choosing a tool
Lists of simple values: explode
If a list holds plain values such as tags, record_path is a poor fit because it expects a list of dicts. Flatten first, then call explode on the list column.
import pandas as pd
posts = [
{"id": 1, "title": "Intro", "tags": ["python", "pandas"]},
{"id": 2, "title": "Advanced", "tags": ["pandas"]},
]
df = pd.json_normalize(posts)
tags = df.explode("tags", ignore_index=True)
print(tags)
# id title tags
# 0 1 Intro python
# 1 1 Intro pandas
# 2 2 Advanced pandasexplode repeats the other columns for each list element. An empty list becomes one row with NaN. A missing key already gives NaN, so explode passes it through unchanged.
Only a few fields: a comprehension
When you need three values out of a deep structure, plain Python is shorter and faster than flattening everything and dropping columns.
users = [
{"id": 1, "name": "Ada", "address": {"city": "London", "geo": {"lat": 51.5}}},
{"id": 2, "name": "Grace", "address": {"city": "New York", "geo": {"lat": 40.7}}},
]
rows = [{"id": u["id"], "city": u["address"]["city"]} for u in users]
df = pd.DataFrame(rows)
print(df.columns.tolist())
# ['id', 'city']The comprehension also lets you handle absent keys explicitly, for example with u.get("address", {}).get("city").
Large inputs: read in chunks
json.loads parses the whole text before json_normalize sees it. For a large file of one record per line (JSON Lines), pd.read_json can stream it in chunks.
import io
import pandas as pd
text = '{"id": 1, "name": "Ada"}\n{"id": 2, "name": "Grace"}\n'
for chunk in pd.read_json(io.StringIO(text), lines=True, chunksize=1):
print(chunk.shape)
# (1, 2)
# (1, 2)Each chunk is a DataFrame, so you can process it and discard it. If a chunk has nested objects, they arrive as dicts in cells. You can pass chunk.to_dict("records") to json_normalize to flatten them. A single large JSON array does not stream this way. For that shape, use a streaming parser such as the third-party ijson package.
read_json versus json_normalize
| Situation | Better choice | Reason |
|---|---|---|
| Flat records or a simple array of objects | `pd.read_json` | One call from text or file to DataFrame |
| Nested objects, dotted column names wanted | `json_normalize` | Flattens leaf values and builds names from key paths |
| List of records inside each parent | `json_normalize` with `record_path` and `meta` | Gives one row per element and keeps parent fields |
| JSON Lines too large for memory | `read_json` with `chunksize` | Reads a bounded number of lines at a time |
read_json does not flatten nested objects. It leaves them as dicts in the cells.
Failure modes to watch
- Using
metafor many parent fields on a very wide record list repeats those values on every row, which multiplies memory use. - Records with different shapes under the same
record_pathproduce columns that are mostlyNaN. Check for this before you aggregate. - Deeply nested lists inside the expanded records stay as lists. You then need a second
explodeor a secondjson_normalizecall.
Exercise
A file has 5 GB of JSON Lines, and each line is one event with a nested "user" object. You need only the columns "event" and "user.id". Which approach fits, and why not call json_normalize on the whole file?
Show answer
Read the file with pd.readjson(path, lines=True, chunksize=N). For each chunk, pull out the two fields, for example with pd.jsonnormalize(chunk.todict("records")) and a column selection, or a comprehension over the records. Keep only the reduced result. Calling jsonnormalize on the whole file means loading all 5 GB as Python objects and then building the full flat table, which uses far more memory than the file size.