Sub topic 9
Carrying parent fields along with meta
This chapter assumes you can already call pd.json_normalize on a list of dictionaries and that you know what record_path does. If not, review the previous chapter first. You should also be comfortable with nested dictionaries and lists in Python.
When record_path expands a list into rows, the parent record's own fields are dropped. The meta parameter copies them back onto every expanded row.
The problem meta solves
Take an order that contains a list of line items. With record_path="items", each item becomes a row. Each row contains only what was inside the item, so the order ID and customer are lost. You can no longer tell which order an item belongs to.
meta lists the parent fields to keep. Each listed value is repeated once for every row produced from that parent.
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}],
},
]
without_meta = pd.json_normalize(orders, record_path="items")
print(without_meta.columns.tolist())
# ['sku', 'qty']
with_meta = pd.json_normalize(
orders,
record_path="items",
meta=["order_id", ["customer", "name"]],
)
print(with_meta.columns.tolist())
# ['sku', 'qty', 'order_id', 'customer.name']
print(len(with_meta))
# 3
print(with_meta.to_dict("records")[1])
# {'sku': 'B2', 'qty': 1, 'order_id': 100, 'customer.name': 'Ada'}Order 100 has two items, so order_id 100 and the name "Ada" appear twice. Order 101 has one item, so it appears once. The result has three rows, one per item.
How meta entries are written
Each entry in the meta list is one of two things.
| Entry | Meaning | Resulting column |
|---|---|---|
| `"order_id"` | A top-level key of the parent record | `order_id` |
| `["customer", "name"]` | A key path into nested objects | `customer.name` |
A string reaches a top-level key. To reach inside a nested object, give a list of keys, one per level. The column name is the keys joined with sep. The default is a dot, so the path above becomes customer.name.
The sep argument applies to meta columns as well as record columns. Setting sep="_" gives customer_name:
df = pd.json_normalize(
orders,
record_path="items",
meta=["order_id", ["customer", "name"]],
sep="_",
)
print(df.columns.tolist())
# ['sku', 'qty', 'order_id', 'customer_name']Note that a dotted string such as "customer.name" does not work as a path. Pandas treats it as one literal key. It would look for a key called customer.name and raise a KeyError. Always use a list for nested paths.
What happens inside the call
For each parent record, pandas does three things:
- It pulls out the list named by
record_pathand flattens each element into a row. - It reads each
metavalue from the parent. - It repeats those meta values once per row from that parent, then adds them as extra columns.
The diagram shows one order becoming rows.
Column order
The output always puts record columns first, in the order the record keys were found. Meta columns follow, in the order you listed them in meta. The order of the meta list is under your control. If you want order_id as the first column, reorder after the call:
df = pd.json_normalize(orders, record_path="items", meta=["order_id"])
df = df[["order_id", "sku", "qty"]]
print(df.columns.tolist())
# ['order_id', 'sku', 'qty']Meta with a multi-level record_path
record_path can be a list of keys when the records sit two or more levels down. Each level of the path can hold its own meta fields. A meta entry is matched to the level that its path length points to.
import pandas as pd
regions = [
{
"region": "EU",
"countries": [
{"name": "France", "cities": [{"city": "Paris", "pop": 2.1}, {"city": "Lyon", "pop": 0.5}]},
{"name": "Spain", "cities": [{"city": "Madrid", "pop": 3.3}]},
],
}
]
df = pd.json_normalize(
regions,
record_path=["countries", "cities"],
meta=["region", ["countries", "name"]],
)
print(df.columns.tolist())
# ['city', 'pop', 'region', 'countries.name']
print(df.to_dict("records")[2])
# {'city': 'Madrid', 'pop': 3.3, 'region': 'EU', 'countries.name': 'Spain'}region is read from the top-level record. countries.name is read from each country object, one level down. Both are repeated onto every city row. This lets you keep the full ancestry of a deeply nested record in one flat table.
Gotchas
Empty lists drop the parent
If a parent's list is empty, it produces zero rows. Its meta values are repeated zero times, so the parent vanishes from the result. This is easy to miss when you count rows.
import pandas as pd
orders = [
{"order_id": 1, "items": [{"sku": "A1"}]},
{"order_id": 2, "items": []},
]
df = pd.json_normalize(orders, record_path="items", meta=["order_id"])
print(len(df))
# 1
print(df["order_id"].tolist())
# [1]If you need every parent to appear, build a parent table and merge it with a right join. The empty parent then gets NaN in the item columns.
parents = pd.DataFrame({"order_id": [o["order_id"] for o in orders]})
full = df.merge(parents, on="order_id", how="right")
print(len(full))
# 2
print(full["sku"].tolist())
# ['A1', nan]Name collisions raise an error
If a record column and a meta column would have the same name, pandas refuses to build the table. Suppose each item has its own id and you also ask for the parent id:
import pandas as pd
data = [{"id": 10, "items": [{"id": "x"}, {"id": "y"}]}]
try:
pd.json_normalize(data, record_path="items", meta=["id"])
except ValueError as e:
print(e)
# Conflicting metadata name id, need distinguishing prefixThe fix is record_prefix or meta_prefix. The next chapter covers them.
Missing meta keys raise KeyError
If any parent lacks a key listed in meta, the call fails with a KeyError by default. The errors="ignore" option fills those values with NaN. A later chapter covers it in detail.
Meta values are copied, not linked
Every repeated value in a row is a reference to the same parent value. If a meta field is itself a dict or a list, each row holds that same object in its cell. Mutating it in one cell changes it in all the rows of that parent. To avoid this, request a leaf value with a key path, such as ["customer", "name"], instead of the whole customer object.
Values are not type-converted
Meta values keep whatever type the JSON gave them. A numeric string stays a string. Convert dtypes after flattening, which a later chapter covers.
Choosing what to put in meta
Keep only the parent fields you need. Each one is duplicated on every row, so a large meta field such as a long text or a big nested object multiplies memory use by the number of child rows. A good rule is to keep identifiers and the few descriptive fields you will group or filter by. Everything else can be joined back later using the ID.
Always include a parent identifier such as order_id. Without one, you cannot join the flattened rows back to the parent table.
Exercise
You run pd.json_normalize(orders, record_path="items", meta=["customer.name"]) on the orders from this chapter and get a KeyError. What is wrong, and how do you fix it?
Show answer
The string "customer.name" is treated as one literal key, which does not exist at the top level of an order. A nested field needs a list of keys, so use meta=[["customer", "name"]]. The column will be named customer.name.
Exercise
Two orders have 3 items and 0 items. You call jsonnormalize with recordpath="items" and meta=["orderid"]. How many rows does the result have, and which orderid values appear?
Show answer
The result has 3 rows. All 3 rows have the orderid of the first order. The second order has an empty list, so it produces no rows, and its orderid never appears.
Exercise
A list of sections contains pages, and each page contains words. You want one row per word, with the section title and the page number on each row. The word records are at ["pages", "words"]. Write the meta argument, assuming the keys are title on a section and number on a page.
Show answer
meta=["title", ["pages", "number"]] along with record_path=["pages", "words"]. The string "title" reads from the top-level section. The list ["pages", "number"] reads from each page object, one level down, and the column is named pages.number.