Sub topic 11
Handling Missing Meta Keys with errors='ignore'
This chapter covers what pd.json_normalize does when a field named in meta is absent from some records, and how the errors parameter changes that. It assumes you can call json_normalize with record_path and meta, and that you know a missing key in a plain record becomes NaN. The earlier chapters on record_path and meta cover both.
The problem: meta is strict by default
When you flatten without record_path, a key missing from one record simply produces NaN in that record's row. Once you pass meta, the rules change. Each name in meta is looked up in every parent record, and by default a failed lookup raises a KeyError.
Real API data often has optional fields such as a coupon code, a middle name, or a nested customer object that only appears for logged-in users. Here is a small dataset where one order has no coupon:
import pandas as pd
orders_partial = [
{"order_id": 1, "coupon": "SAVE10", "items": [{"sku": "A1"}]},
{"order_id": 2, "items": [{"sku": "B2"}]},
]
try:
pd.json_normalize(
orders_partial,
record_path="items",
meta=["order_id", "coupon"],
)
except KeyError as err:
print("KeyError:", err)The call fails. The error message names the missing key (coupon) and suggests passing errors='ignore'. The failure is deliberate. A missing parent field is often a sign of a bad export or a typo, and raising an error stops you from building a table with silent gaps.
Using errors='ignore'
The errors parameter accepts two values.
| Value | Behavior when a meta key is missing |
|---|---|
| `"raise"` (default) | Raises `KeyError` and names the key |
| `"ignore"` | Fills that cell with `NaN` and continues |
Set it to "ignore" when the field is genuinely optional:
import pandas as pd
orders_partial = [
{"order_id": 1, "coupon": "SAVE10", "items": [{"sku": "A1"}]},
{"order_id": 2, "items": [{"sku": "B2"}]},
]
df = pd.json_normalize(
orders_partial,
record_path="items",
meta=["order_id", "coupon"],
errors="ignore",
)
print(df)
# sku order_id coupon
# 0 A1 1 SAVE10
# 1 B2 2 NaNThe coupon column exists even though only one record supplied it. Order 2 has NaN there. Every child row copied from a parent inherits that parent's value, so an order with five items and no coupon yields five NaN cells.
Nested meta paths
A meta entry can be a list of keys that walks into nested objects, such as ["customer", "name"]. With errors="ignore", a break anywhere along the path gives NaN. This covers a missing customer object, as well as a customer object that lacks name.
import pandas as pd
orders = [
{
"order_id": 1,
"customer": {"name": "Ada"},
"items": [{"sku": "A1"}],
},
{
"order_id": 2,
"items": [{"sku": "B2"}, {"sku": "C3"}],
},
{
"order_id": 3,
"customer": {},
"items": [{"sku": "D4"}],
},
]
df = pd.json_normalize(
orders,
record_path="items",
meta=["order_id", ["customer", "name"]],
errors="ignore",
)
print(df.columns.tolist())
# ['sku', 'order_id', 'customer.name']
print(df["customer.name"].tolist())
# ['Ada', nan, nan, nan]Order 2 has no customer key at all, and order 3 has an empty customer object. Both produce NaN, and order 2 produces it twice because it has two items.
What errors='ignore' does not cover
The parameter is narrow. Three cases are easy to misread.
It applies to meta, not record_path
errors governs the lookup of meta fields. If a record lacks the key named in record_path, pandas still raises a KeyError in current versions, because there is nothing to expand into rows. If you expect some parents to have no list, give them an empty list or a null value first. Pandas treats a null list as zero child rows.
Parents with no children disappear
With record_path, each row comes from a child element. A parent whose list is empty contributes zero rows, so its meta values never appear in the output. errors="ignore" does not change this.
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(df["order_id"].tolist())
# [1]Order 2 is gone. If you need a row for every parent, normalize the parents separately (without record_path) and merge.
A null parent is not a missing key
errors="ignore" handles absent keys. If customer is present but set to null, the lookup tries to index into None. That is a different kind of failure, and errors does not cover it. Replace the null with {} before normalizing. You can do that in a loop: rec["customer"] = rec.get("customer") or {}.
The risk: typos pass silently
Because errors="ignore" turns every failed lookup into NaN, a misspelled meta name no longer raises an error. You get an all-NaN column:
import pandas as pd
orders_partial = [
{"order_id": 1, "coupon": "SAVE10", "items": [{"sku": "A1"}]},
{"order_id": 2, "items": [{"sku": "B2"}]},
]
df = pd.json_normalize(
orders_partial,
record_path="items",
meta=["order_id", "coupn"], # typo
errors="ignore",
)
print(df["coupn"].isna().all())
# TrueNothing warns you. Two habits reduce this risk:
- Only turn on
errors="ignore"after the default run has failed on a key you know is optional. - Check the result, for example that an optional column is not entirely empty.
import pandas as pd
def normalize_orders(data, optional_meta):
df = pd.json_normalize(
data,
record_path="items",
meta=["order_id", *optional_meta],
errors="ignore",
)
for col in optional_meta:
if df[col].isna().all():
raise ValueError(f"Optional field {col!r} is empty in every row; check the name")
return df
orders_partial = [
{"order_id": 1, "coupon": "SAVE10", "items": [{"sku": "A1"}]},
{"order_id": 2, "items": [{"sku": "B2"}]},
]
df = normalize_orders(orders_partial, ["coupon"])
print(df["coupon"].tolist())
# ['SAVE10', nan]The guard cannot tell a typo from a truly empty field. It turns a silent problem into a visible one, and you can decide what to do.
Consequences for dtypes
NaN is a float. If a meta field holds integers and some parents lack it, the column becomes float64 (or object if other values are strings). Counts such as qty or year then display as 3.0 and NaN. The cleanup chapter covers conversion. For now, remember that a missing value can change a column's type, not just leave a blank.
import pandas as pd
data = [
{"id": 1, "priority": 3, "items": [{"sku": "A1"}]},
{"id": 2, "items": [{"sku": "B2"}]},
]
df = pd.json_normalize(data, record_path="items", meta=["id", "priority"], errors="ignore")
print(df["id"].dtype, df["priority"].dtype)
# int64 float64To keep integers, convert with the nullable type: df["priority"] = df["priority"].astype("Int64"). This keeps missing entries as <NA>.
Alternatives to errors='ignore'
errors="ignore" always fills NaN. If you want a different default, such as "none" or 0, you have two options.
- Fill after normalizing:
df["coupon"] = df["coupon"].fillna("none"). - Fill before normalizing:
rec.setdefault("coupon", "none")for each record. This also lets you keep the strict default for every other meta key, so typos still raise.
The second option is often the better choice for a pipeline. You declare which fields are optional and give each a default. Everything else stays strict.
import pandas as pd
orders_partial = [
{"order_id": 1, "coupon": "SAVE10", "items": [{"sku": "A1"}]},
{"order_id": 2, "items": [{"sku": "B2"}]},
]
for rec in orders_partial:
rec.setdefault("coupon", "none")
df = pd.json_normalize(
orders_partial,
record_path="items",
meta=["order_id", "coupon"],
)
print(df["coupon"].tolist())
# ['SAVE10', 'none']Summary of behavior
- By default, a meta key missing from any parent record raises
KeyError. errors="ignore"replaces each missing meta value withNaN, including values behind a nested path such as["customer", "name"].- It does not cover a missing
record_pathkey, anullparent object, or parents whose list is empty. - It turns typos into all-
NaNcolumns, so validate the result. NaNcan convert integer columns to floats.
Exercise
You run pd.json_normalize(data, record_path="items", meta=["order_id", "coupon"], errors="ignore") on a list of 200 orders. The resulting coupon column is NaN in all rows, though you know many orders have a coupon. Name two likely causes and one way to detect the problem early.
Show answer
Likely causes: the name in meta does not match the key in the data (for example coupn or a different case such as Coupon), or the field is nested under another object (for example discount.coupon) and needs a list path like ["discount", "coupon"]. Because errors="ignore" turns every failed lookup into NaN, no error is raised. To detect it, first run without errors="ignore" so a KeyError names the missing key, or check afterwards that the column is not entirely empty with df["coupon"].isna().all().
Exercise
Given data = [{"id": 1, "items": [{"sku": "A"}]}, {"id": 2, "items": []}, {"id": 3, "tags": [], "items": [{"sku": "B"}, {"sku": "C"}]}], how many rows does pd.json_normalize(data, record_path="items", meta=["id", "tags"], errors="ignore") return, and what are the values of the tags column?
Show answer
It returns 3 rows. Order 2 has an empty items list and contributes no rows. Order 1 has no tags key, so its row gets NaN. Order 3 has an empty list in tags, which is present, so its two rows both hold []. The tags values are therefore [nan, [], []].