Sub topic 3
Carrying Parent Fields with `meta`
Assume you know Python dictionaries and lists, can create a pandas DataFrame, and understand that JSON objects become dictionaries. In json_normalize, record_path expands a nested list into rows. The meta argument copies fields from each parent object onto those rows.
import pandas as pd
orders = [
{
"order_id": 100,
"customer": {"name": "Ada"},
"items": [{"sku": "A1", "qty": 2}, {"sku": "B2", "qty": 1}],
},
{
"order_id": 101,
"customer": {"name": "Grace"},
"items": [{"sku": "A1", "qty": 5}],
},
]
df = pd.json_normalize(
orders,
record_path="items",
meta=["order_id", ["customer", "name"]],
)
print(df)The result has three rows. Each item row includes its parent order ID and customer name. A nested metadata path uses a list of keys, such as ["customer", "name"].
Preventing Column Collisions
Record fields and metadata can have the same name. Prefixes make their origins clear:
df = pd.json_normalize(
orders,
record_path="items",
meta=["order_id"],
record_prefix="item_",
meta_prefix="order.",
)
print(df.columns.tolist())
# ['item_sku', 'item_qty', 'order.order_id']record_prefix changes columns created from list elements. meta_prefix changes columns copied from parents.
Missing Metadata and Cleanup
A missing metadata key raises KeyError by default. Use errors="ignore" when the field is optional. Missing values become NaN, so inspect and handle them before analysis.
After flattening, rename columns to match your project’s naming convention and convert numeric strings explicitly:
df = pd.json_normalize(
[{"id": 1, "items": [{"price": "4.50"}]}],
record_path="items",
meta=["id", "coupon"],
errors="ignore",
)
df = df.rename(columns={"item.price": "price"}) if "item.price" in df else df
df["price"] = pd.to_numeric(df["price"])When to Use Another Tool
Use explode when you already have a DataFrame and only need to turn one list column into rows. Use pd.read_json for regular JSON records that need little shaping. For deeply irregular or very large documents, parse in stages or use a streaming parser. json_normalize builds an in-memory DataFrame, so it is not a complete solution for unlimited input.
Exercise
Which argument keeps the parent field order_id when items becomes one row per item?
Show answer
Pass meta=["order_id"] together with record_path="items".