Sub topic 2
Flattening Only to a Chosen Depth with `max_level`
Assume you know basic Python dictionaries and lists, can create a pandas DataFrame, and understand that JSON objects become dictionaries while JSON arrays become lists.
Stop Flattening at a Chosen Depth
pd.json_normalize normally follows nested dictionaries all the way to their leaf values. Use max_level to stop after a specific number of nested levels.
import pandas as pd
users = [
{
"id": 1,
"name": "Ada",
"address": {
"city": "London",
"geo": {"lat": 51.5, "lng": -0.12},
},
}
]
df = pd.json_normalize(users, max_level=1)
print(df.columns.tolist())
print(df["address.geo"].iloc[0])['id', 'name', 'address.city', 'address.geo']
{'lat': 51.5, 'lng': -0.12}Here, address is flattened, but the deeper geo object remains a dictionary in one cell. This is useful when the remaining object has its own meaning or should be processed separately.
Records with Different Keys
JSON records do not need identical keys. If a key is missing from one record, pandas creates the column and puts NaN in the missing position.
records = [
{"id": 1, "title": "Intro", "tags": ["python", "pandas"]},
{"id": 2, "title": "Advanced"},
]
df = pd.json_normalize(records)
print(df) id title tags
0 1 Intro [python, pandas]
1 2 Advanced NaNNaN means that the value is unavailable. Decide later whether it means “missing,” “not applicable,” or an empty collection.
Lists Stay as Values by Default
A list inside a record is not automatically turned into multiple rows. It remains a list-valued cell. This preserves the original record shape, but it can make filtering or aggregation less convenient.
Expand a List with `record_path`
Use record_path when a list represents repeated records, such as order items. Each list element becomes a row. Use meta to copy parent fields onto those rows.
orders = [
{
"order_id": 100,
"customer": {"name": "Ada"},
"items": [{"sku": "A1", "qty": 2}, {"sku": "B2", "qty": 1}],
}
]
df = pd.json_normalize(
orders,
record_path="items",
meta=["order_id", ["customer", "name"]],
)
print(df) sku qty order_id customer.name
0 A1 2 100 Ada
1 B2 1 100 AdaExercise
Which argument expands items into one row per item while retaining order_id?
Show answer
Use record_path="items" and include "order_id" in meta.