Sub topic 9
Carrying parent fields along with meta
This chapter assumes you can write basic Python and pandas, and that you know how record_path expands a list of records into rows. Here you will learn how meta copies fields from the parent record onto each of those rows.
Why you need meta
When record_path expands a list, each element becomes a row. The columns come only from the elements themselves. Everything else in the parent record is dropped, including the order ID that tells you which order an item belongs to.
Here is the data used in this chapter:
import pandas as pd
orders = [
{
"order_id": 100,
"customer": {"id": 1, "name": "Ada"},
"items": [{"sku": "A1", "qty": 2}, {"sku": "B2", "qty": 1}],
},
{
"order_id": 101,
"customer": {"id": 2, "name": "Grace"},
"items": [{"sku": "A1", "qty": 5}],
},
]
df = pd.json_normalize(orders, record_path="items")
print(df)The output has three rows and two columns, sku and qty. You cannot tell which order each row came from.
Adding parent fields with meta
The meta argument takes a list of parent fields. json_normalize copies each one onto every row produced from that parent.
df = pd.json_normalize(
orders,
record_path="items",
meta=["order_id"],
)
print(df)
# sku qty order_id
# 0 A1 2 100
# 1 B2 1 100
# 2 A1 5 101Order 100 has two items, so order_id 100 appears twice. The record columns come first, and the meta columns follow in the order you listed them.
Reaching nested parent fields
A parent field may sit inside a nested object. To reach it, give meta a list of keys that spells out the path. The column name joins the keys with a dot.
df = pd.json_normalize(
orders,
record_path="items",
meta=["order_id", ["customer", "name"]],
)
print(df.columns.tolist())
# ['sku', 'qty', 'order_id', 'customer.name']
print(len(df))
# 3A plain string such as "order_id" selects a top-level key. A list such as ["customer", "name"] walks down one key at a time. The sep argument from earlier chapters also applies here, so sep="_" would give customer_name.
Common errors
- Naming a nested field with a dotted string.
meta=["customer.name"]looks for a top-level key literally calledcustomer.name. It does not find one, and you get aKeyError. Use["customer", "name"]. - Choosing a field that is not in every record. By default a missing meta key raises a
KeyError. Theerrors="ignore"option, covered in a later chapter, fills inNaNinstead. - Passing a parent field that is itself a list. The list is copied as one value onto each row. This works, but it repeats the whole list on every row and uses more memory than you may expect.
- Expecting meta to work without record_path. Without
record_path, the function already keeps every field, sometahas no purpose.
Checking the result
Because meta repeats values, the row count equals the total number of list elements across all parents, not the number of parents. A quick check protects you from silent mistakes:
expected = sum(len(o["items"]) for o in orders)
assert len(df) == expectedIf a parent has an empty list, it contributes no rows, and its meta values do not appear at all. Keep that in mind if you later count orders from the flattened table.
Exercise
Using the orders data, write a json_normalize call that returns one row per item with the columns sku, qty, order_id, and the customer's id. What is the name of the customer id column?
Show answer
Use pd.json_normalize(orders, record_path="items", meta=["order_id", ["customer", "id"]]). The customer id column is named customer.id, because the nested key path is joined with a dot.
Exercise
Why does meta=["customer.name"] raise a KeyError, and how do you fix it?
Show answer
meta treats a string as one top-level key, and no top-level key is named customer.name. Pass the path as a list of keys instead: meta=[["customer", "name"]].