Sub topic 13
When json_normalize is not the right tool
This chapter assumes you have read the earlier chapters of this tutorial. You should know json_normalize with record_path and meta, how NaN appears for missing keys, and how to rename columns and convert dtypes afterwards. You should also be comfortable with Python dicts, lists, and basic DataFrame operations.
json_normalize is the right default for flattening nested objects and expanding one list of records. It is not the only tool, and sometimes it is the wrong one. This chapter covers the cases where DataFrame.explode, pd.read_json, a plain Python loop, or a streaming approach fits better.
What json_normalize does and does not do
json_normalize takes Python objects that are already in memory: a dict or a list of dicts. It does three things.
- It flattens nested objects into dotted column names.
- It can expand one list of records into rows, using
record_path. - It copies chosen parent fields onto those rows, using
meta.
It does not parse JSON text, and it does not read files. It also does not stream. It does not expand several independent lists in one call, and it does not convert dtypes. Each of these gaps points to an alternative.
explode: when the data is already a table
DataFrame.explode turns each element of a list-valued column into its own row. All other columns repeat. Use it when the data is already in a DataFrame, for example after pd.DataFrame(posts) or after you flattened with json_normalize and a column still holds lists.
import pandas as pd
posts = [
{"id": 1, "title": "Intro", "tags": ["python", "pandas"]},
{"id": 2, "title": "Advanced", "tags": ["pandas"]},
{"id": 3, "title": "Draft", "tags": []},
]
df = pd.DataFrame(posts)
tags = df.explode("tags", ignore_index=True)
print(tags.shape)
# (4, 3)
print(tags["tags"].tolist())
# ['python', 'pandas', 'pandas', nan]Two details matter here.
- Without
ignore_index=True, the repeated rows keep the original index label. That is useful if you want to join back to the source row, and confusing if you do not expect it. - An empty list becomes one row with
NaN.record_pathbehaves differently. A record whose list is empty produces no rows at all.
explode with lists of dicts
explode leaves each element as it was. If the elements are dicts, you get a column of dicts. You then flatten that column with json_normalize and put the pieces back together. This reproduces what record_path and meta do, but it lets you flatten the parent and the children separately.
import pandas as pd
orders = [
{"order_id": 100, "items": [{"sku": "A1", "qty": 2}, {"sku": "B2", "qty": 1}]},
{"order_id": 101, "items": [{"sku": "A1", "qty": 5}]},
{"order_id": 102, "items": []},
]
df = pd.DataFrame(orders).explode("items", ignore_index=True)
df = df.dropna(subset=["items"]).reset_index(drop=True)
items = pd.json_normalize(df["items"])
result = pd.concat([df[["order_id"]], items], axis=1)
print(result.columns.tolist())
# ['order_id', 'sku', 'qty']
print(len(result))
# 3The dropna step is required. Order 102 has an empty list, so explode gives it a single NaN cell, and json_normalize cannot flatten a NaN. The reset_index keeps the two frames aligned in concat, because json_normalize returns a fresh RangeIndex.
Prefer explode over record_path in these cases:
- You already have a DataFrame and the list column is one of many columns.
- You need to explode more than one level of lists in stages and inspect the data between stages.
- You want to keep rows whose list is empty. In that case, skip the
dropna.
Prefer record_path and meta when you start from raw Python objects and want the result in one call.
pd.read_json: parsing, not flattening
pd.read_json reads JSON text or a file straight into a DataFrame. It handles the parsing step, so you do not call json.loads yourself. It does not flatten nested objects.
from io import StringIO
import pandas as pd
text = '[{"id": 1, "address": {"city": "London"}}, {"id": 2, "address": {"city": "New York"}}]'
df = pd.read_json(StringIO(text))
print(df.columns.tolist())
# ['id', 'address']
print(df["address"].iloc[0])
# {'city': 'London'}The address column holds dicts. To flatten them, you still need json_normalize. In that case read_json adds nothing, and json.loads followed by json_normalize is the clearer path.
read_json is the better choice in these cases:
- The JSON is already flat, such as a list of records with scalar values. One call gives you a DataFrame.
- The input is JSON Lines, with one object per line. Pass
lines=True. - You want pandas to convert dtypes during parsing. By default,
read_jsontries to infer dates and numeric types. That is convenient, and it can surprise you, for example when a column of ID strings is converted to numbers. Passdtype=Falseor an explicitdtypemapping to control it. - You need
chunksizewithlines=Trueto read a file in pieces.
Note that wrapping literal text in StringIO is the current way to pass a JSON string. Passing a bare string is deprecated in recent pandas versions.
A list comprehension when you need few fields
A JSON document may have hundreds of nested keys while you need three. json_normalize flattens everything, creating columns you then drop. Selecting fields yourself is simpler and faster.
import pandas as pd
users = [
{"id": 1, "address": {"city": "London"}, "plan": {"tier": "pro"}},
{"id": 2, "address": None, "plan": {"tier": "free"}},
]
rows = [
{"id": u["id"], "city": (u.get("address") or {}).get("city")}
for u in users
]
df = pd.DataFrame(rows)
print(df.to_dict("records"))
# [{'id': 1, 'city': 'London'}, {'id': 2, 'city': None}]The pattern (u.get("address") or {}) handles both a missing key and an explicit null. This is the case where u.get("address", {}) would fail, because it returns None when the key exists with a null value.
The cost is that you now own the missing-key logic. For a small number of known fields that is a good trade. For an unknown or changing schema, json_normalize discovers the columns for you, which is its main advantage.
Large inputs
json_normalize needs the whole parsed structure in memory. If you load a large file with json.load, you hold the Python objects, and then the DataFrame holds a second copy. Python dicts are memory-heavy, so the in-memory objects can be several times the size of the file on disk.
Two options help.
- Use JSON Lines and process in batches. Parse one line at a time, normalize a batch, keep only the columns you need, and discard the batch.
- Use a streaming parser. A library such as
ijsonyields items from one large JSON array without loading all of it. You can then batch those items in the same way.
Here is the batch approach for a JSON Lines file:
import json
import pandas as pd
def read_flat(path, columns, batch_size=50_000):
parts = []
batch = []
with open(path, encoding="utf-8") as f:
for line in f:
batch.append(json.loads(line))
if len(batch) >= batch_size:
parts.append(pd.json_normalize(batch).reindex(columns=columns))
batch = []
if batch:
parts.append(pd.json_normalize(batch).reindex(columns=columns))
return pd.concat(parts, ignore_index=True)
with open("events.jsonl", "w", encoding="utf-8") as f:
f.write('{"id": 1, "user": {"name": "Ada"}, "debug": {"trace": "x"}}\n')
f.write('{"id": 2, "user": {"name": "Grace"}}\n')
df = read_flat("events.jsonl", ["id", "user.name"], batch_size=1)
print(df.to_dict("records"))
# [{'id': 1, 'user.name': 'Ada'}, {'id': 2, 'user.name': 'Grace'}]reindex(columns=columns) does two jobs. It drops fields you did not ask for, and it creates a NaN column if a batch lacks a field. Plain [columns] would raise a KeyError in that second case. Because every batch ends up with the same columns, concat produces a clean result.
Limits that no option fixes
Some problems are not about picking a different pandas function.
| Situation | Why json_normalize struggles | What to do |
|---|---|---|
| Two sibling lists, such as `items` and `payments`, in each record | `record_path` expands only one list per call | Run `json_normalize` twice with the same `meta`, and keep the results as two tables |
| Lists inside lists | Each `record_path` step expands one level into a flat table, and you then need to carry keys along by hand | Expand in stages with `explode`, or normalize each level separately |
| Keys that vary per record, such as IDs used as keys (`{"u123": {...}}`) | Every distinct key becomes its own column | Convert the dict to a list of records first, using `[{"key": k, **v} for k, v in d.items()]` |
| Data you want to keep nested, such as a JSON column in a database | Flattening loses the structure and widens the table | Keep the column as dicts, or store it as JSON text |
| Many-to-many structure | One flat table repeats values and hides the relationships | Build separate related tables and join them on a key |
The "two sibling lists" row deserves a warning. If you try to force both lists into one flat table, you get a cross product, and the row count multiplies. Separate tables joined on an ID are almost always the better design.
Summary of choices
| Need | Best fit |
|---|---|
| Nested objects to columns, data in memory | `json_normalize` |
| One list of records to rows, plus parent fields | `json_normalize` with `record_path` and `meta` |
| List column in an existing DataFrame | `explode` |
| Flat JSON text or file, or JSON Lines | `pd.read_json` |
| A few known fields from a messy document | List comprehension, then `pd.DataFrame` |
| Input larger than comfortable memory | Batches or a streaming parser, keeping only needed columns |
Exercise
A DataFrame has a column tags holding lists. Row 3 has an empty list []. After df.explode("tags"), what does row 3 contain in the tags column, and how does that differ from json_normalize with record_path="tags" on the same data as raw records?
Show answer
explode keeps row 3 and puts NaN in tags. record_path produces no rows for a record whose list is empty, so that record disappears from the result.
Exercise
You have a 4 GB JSON Lines file with 200 fields per record, and you need only id and user.name. Why can pd.json_normalize(list_of_all_records) fail, and what change fixes it?
Show answer
It needs every parsed record in memory at once, and Python dicts take far more memory than the file size suggests. Read the file line by line, normalize in batches, keep only the needed columns with reindex(columns=[...]), and concat the small results.