Sub topic 6
What happens when records have different keys
Real JSON rarely has the same keys in every record. An API may leave out a field when it has no value, and an older record may predate a newer field. This chapter covers how pd.json_normalize handles records whose keys differ, and which cases it does not handle quietly.
It assumes you know how json_normalize turns nested objects into dotted column names, and that you can read a DataFrame's columns, dtypes, and isna() output.
The default rule: union of keys, gaps become NaN
When you call json_normalize on a list of dicts, the result has one column for every flattened key seen in any record. A record that lacks a key gets NaN in that column. Nothing is dropped and nothing raises an error.
import pandas as pd
users = [
{"id": 1, "name": "Ada", "email": "[email protected]"},
{"id": 2, "name": "Grace", "phone": "555-0101"},
{"id": 3, "name": "Linus", "email": "[email protected]", "phone": "555-0102"},
]
df = pd.json_normalize(users)
print(df.columns.tolist())
# ['id', 'name', 'email', 'phone']
print(df.isna().sum().to_dict())
# {'id': 0, 'name': 0, 'email': 1, 'phone': 1}Columns appear in the order each key is first seen. email comes before phone because record 1 has email and record 2 is the first to add phone. Do not rely on this order for downstream code. If the order matters, select the columns explicitly, as shown later in this chapter.
Missing keys at different nesting levels
The same rule applies after flattening. A key counts as missing if its full dotted path is absent, whatever the reason. The parent object may be absent, or the parent may exist without that child.
import pandas as pd
records = [
{"id": 1, "address": {"city": "London", "geo": {"lat": 51.5}}},
{"id": 2, "address": {"city": "Paris"}},
{"id": 3},
]
df = pd.json_normalize(records)
print(df.columns.tolist())
# ['id', 'address.city', 'address.geo.lat']
print(df["address.city"].isna().tolist())
# [False, False, True]
print(df["address.geo.lat"].isna().tolist())
# [False, True, True]Record 2 has an address but no geo. Record 3 has no address at all. Both produce NaN in address.geo.lat, so after flattening you cannot tell which of the two happened. If that distinction matters, check the raw data before you normalize it.
An explicit null is not the same as a missing key
JSON can write "address": null. In Python that is None, a value, not an absent key. json_normalize only flattens dict values, so a None stays under the parent's own name instead of being flattened into dotted columns.
import pandas as pd
records = [
{"id": 1, "address": {"city": "London"}},
{"id": 2, "address": None},
]
df = pd.json_normalize(records)
print(df.columns.tolist())
# ['id', 'address.city', 'address']
print(df["address"].isna().tolist())
# [True, True]You now have two columns for one concept. address.city holds the real data, and address is a nearly empty leftover from the null. A frame like this looks fine until you drop or rename columns and the leftover causes trouble.
Replace None with an empty dict before normalizing. An empty dict flattens to nothing, so no leftover column appears.
import pandas as pd
records = [
{"id": 1, "address": {"city": "London"}},
{"id": 2, "address": None},
]
cleaned = [{**r, "address": r.get("address") or {}} for r in records]
df = pd.json_normalize(cleaned)
print(df.columns.tolist())
# ['id', 'address.city']
print(df["address.city"].tolist())
# ['London', nan]The r.get("address") or {} expression handles both a missing key and an explicit None. It would also replace other falsy values, such as 0 or "", so use it only on fields that are meant to be objects.
Side effect: integer columns become floats
NaN is a float value. If a numeric column has gaps, pandas stores the whole column as float64, even if every present value is a whole number.
import pandas as pd
df = pd.json_normalize([{"id": 1, "score": 10}, {"id": 2}])
print(df.dtypes)
# id int64
# score float64
# dtype: objectscore now holds 10.0 and NaN. If you need integers, convert the column to pandas' nullable integer type, which represents the gap as <NA> and keeps the integers intact.
import pandas as pd
df = pd.json_normalize([{"id": 1, "score": 10}, {"id": 2}])
df["score"] = df["score"].astype("Int64")
print(df["score"])
# 0 10
# 1 <NA>
# Name: score, dtype: Int64Do this conversion after flattening, as part of cleanup. A later chapter covers dtype conversion in more detail.
Making the column set predictable
The union rule means the columns depend on the data. A page of API results that happens to have no phone values produces a frame with no phone column, and any code that reads df["phone"] then fails with a KeyError. Two tools make the schema stable.
Use reindex with an explicit list of columns. It adds any missing column filled with NaN, drops columns you did not list, and fixes the order.
import pandas as pd
users = [
{"id": 1, "name": "Ada", "email": "[email protected]"},
{"id": 2, "name": "Grace"},
]
expected = ["id", "name", "email", "phone"]
df = pd.json_normalize(users).reindex(columns=expected)
print(df.columns.tolist())
# ['id', 'name', 'email', 'phone']
print(df["phone"].isna().all())
# TrueUse fillna with a dict to supply per-column defaults instead of NaN.
import pandas as pd
df = pd.json_normalize([{"id": 1, "email": "[email protected]"}, {"id": 2}])
df = df.fillna({"email": "unknown"})
print(df["email"].tolist())
# ['[email protected]', 'unknown']Only fill a column when a default is a true value for your analysis. A placeholder like "unknown" or 0 is easy to mistake for real data, and NaN often carries the right meaning of "not provided".
When missing keys raise errors instead
Unions and NaN are only the behavior for plain flattening. Once you use record_path and meta, two kinds of missing key raise a KeyError.
| Situation | Default behavior | How to handle it |
|---|---|---|
| A key inside a flattened record is missing | `NaN` in that column | Nothing needed |
| A `meta` key is missing from some record | `KeyError` | Pass `errors="ignore"` (covered in a later chapter) |
| The `record_path` key is missing from some record | `KeyError` | Supply a default or filter the records first |
The errors parameter applies to meta only. It does not rescue a missing record_path, because a record without the list has nothing to expand into rows. You must repair that case in the data.
import pandas as pd
orders = [
{"order_id": 1, "items": [{"sku": "A1"}, {"sku": "B2"}]},
{"order_id": 2},
{"order_id": 3, "items": []},
]
try:
pd.json_normalize(orders, record_path="items", meta=["order_id"])
except KeyError:
print("KeyError: some records have no 'items'")
# KeyError: some records have no 'items'
fixed = [{**o, "items": o.get("items", [])} for o in orders]
df = pd.json_normalize(fixed, record_path="items", meta=["order_id"])
print(df)
# sku order_id
# 0 A1 1
# 1 B2 1Giving each order an empty list makes the call succeed. Orders 2 and 3 contribute no rows, because a record with zero elements has nothing to expand into rows. If you need to keep those orders in the result, normalize them separately, or build a one-row placeholder for each with a missing sku before you normalize.
Elements inside the record_path list follow the plain rule again. If one item has a qty key and another does not, qty is a column and the second item gets NaN.
Summary of the rules
- Plain flattening creates a column for every key path seen in any record, and fills gaps with
NaN. - A missing parent and a missing child look the same afterward.
- An explicit
nullwhere an object was expected leaves a stray column named after the parent. Replace it with{}first. - Gaps turn integer columns into
float64. UseInt64to restore integers. reindexandfillnamake the schema and defaults explicit.- With
record_path, a missingmetakey and a missingrecord_pathkey both raiseKeyError. Only themetacase is fixed byerrors="ignore".
Exercise
You normalize [{"id": 1, "profile": {"age": 30}}, {"id": 2, "profile": None}, {"id": 3}] with pd.json_normalize. Which columns do you get, and what is a reliable way to avoid the extra column?
Show answer
You get ['id', 'profile.age', 'profile']. Record 2 has an explicit None under profile, and json_normalize only flattens dicts, so the None stays in a column named profile. Record 3 has no profile key, so it only produces NaN in profile.age. To avoid the extra column, replace falsy profile values with an empty dict before normalizing, for example [{**r, "profile": r.get("profile") or {}} for r in data]. The result then has only ['id', 'profile.age'].
Exercise
A list of orders, each with an items list and an order_id, includes some orders with no items key at all. pd.json_normalize(orders, record_path="items", meta=["order_id"], errors="ignore") still raises a KeyError. Why, and what two steps would you take to fix the data and confirm nothing was lost?
Show answer
errors="ignore" only applies to missing meta keys. A missing record_path key always raises, because a record with no list has nothing to expand. Fix it by giving each order a default, for example fixed = [{**o, "items": o.get("items", [])} for o in orders], and normalize fixed. Orders with an empty list produce no rows, so afterward compare df["order_id"].nunique() with len(orders) to see how many orders produced no rows.