Sub topic 4
How Nested Keys Become Column Names, and Changing the Separator
This chapter assumes you can read Python dictionaries and lists and that you have already run pd.json_normalize on a list of records. You should also know what a DataFrame column is. Here you will learn the rule that turns a path of nested keys into one column name, how sep changes that rule, and what can go wrong when you change it.
The naming rule
json_normalize walks each record and descends into every value that is a dictionary. For each leaf value (a number, string, boolean, None, or list) it builds a column name by joining the keys on the way down. Top-level keys keep their own name. Keys below the top level are joined to their parent path with the separator.
import pandas as pd
users = [
{"id": 1, "name": "Ada", "address": {"city": "London", "geo": {"lat": 51.5, "lng": -0.12}}},
{"id": 2, "name": "Grace", "address": {"city": "New York", "geo": {"lat": 40.7, "lng": -74.0}}},
]
df = pd.json_normalize(users)
print(df.columns.tolist())
# ['id', 'name', 'address.city', 'address.geo.lat', 'address.geo.lng']
print(df.loc[0, "address.geo.lat"])
# 51.5The column address.geo.lat comes from the key path address → geo → lat. The column name is only a label. The DataFrame has no hierarchy, and the dots are ordinary characters in a string.
The rule has three consequences.
- The number of columns equals the number of distinct leaf paths across all records. Records with different shapes produce the union of their paths.
- Column order follows the order in which keys first appear.
- Depth does not change the rule. A leaf five levels down gets a name with five segments.
You can also pass a single dictionary instead of a list. pd.json_normalize({"a": {"b": 1}}) returns a one-row DataFrame with the column a.b.
Changing the separator with `sep`
The default separator is ".". The sep argument replaces it. Any string works, including strings longer than one character.
df_sep = pd.json_normalize(users, sep="_")
print(df_sep.columns.tolist())
# ['id', 'name', 'address_city', 'address_geo_lat', 'address_geo_lng']
df_dunder = pd.json_normalize(users, sep="__")
print(df_dunder.columns.tolist())
# ['id', 'name', 'address__city', 'address__geo__lat', 'address__geo__lng']sep affects every name that json_normalize builds from a key path. That includes nested fields inside record_path records and nested meta paths, which are covered in later chapters. The example below uses record_path and meta ahead of those chapters, so you can see that sep applies to them too.
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}],
},
]
default = pd.json_normalize(orders, record_path="items", meta=["order_id", ["customer", "name"]])
print(default.columns.tolist())
# ['sku', 'qty', 'order_id', 'customer.name']
underscored = pd.json_normalize(
orders, record_path="items", meta=["order_id", ["customer", "name"]], sep="_"
)
print(underscored.columns.tolist())
# ['sku', 'qty', 'order_id', 'customer_name']The nested meta entry ["customer", "name"] is a key path, so it is joined with sep in the same way as the dictionary keys.
Which separator should you pick?
| Separator | Example column | Works well for | Watch out for |
|---|---|---|---|
| `"."` (default) | `address.geo.lat` | Quick inspection, matches the JSON path style | Attribute access fails, and `query()` needs backticks |
| `"_"` | `address_geo_lat` | Valid Python identifiers, attribute access, SQL column names | Collides with keys that already contain underscores |
| `"__"` | `address__geo__lat` | Keeping segments distinguishable when keys contain `_` | Long names |
| `"/"` | `address/geo/lat` | Path-like labels | Awkward in most downstream tools |
The choice matters most when the columns leave pandas. If you write to a database or a file that a colleague will query, a name with dots often needs quoting. A name with underscores usually does not.
How the separator affects your code
With dotted names you cannot use attribute access, because df.address.city looks for a column named address, which does not exist. Bracket access works.
df = pd.json_normalize(users)
print(df["address.city"].tolist())
# ['London', 'New York']
# df.address.city -> AttributeErrorDataFrame.query reads a dot as attribute access, so a dotted column name must be wrapped in backticks.
print(df.query("`address.city` == 'London'")["name"].tolist())
# ['Ada']With sep="_", the same columns are valid identifiers and you can write df.address_city. Attribute access has its own limits. It does not work if a column name collides with a DataFrame method such as count, and it cannot be used to assign a new column. Bracket access is the safer habit in scripts.
Collisions: when two paths produce the same name
The separator is not reserved in your data. If a key already contains the separator, two different paths can produce the same column name. json_normalize does not raise an error or add a suffix. One value silently replaces the other.
record = [{"address_city": "Paris", "address": {"city": "London"}}]
df = pd.json_normalize(record, sep="_")
print(df.columns.tolist())
# ['address_city']
print(df.shape)
# (1, 1)The input has two leaf values, but the output has one column and one cell. The same thing happens with the default separator if a key contains a literal dot, for example {"address.city": "Paris", "address": {"city": "London"}}.
You can detect this by comparing the number of leaf values in one record with the number of columns. The helper below counts leaves in a single record.
def count_leaves(obj):
if isinstance(obj, dict):
return sum(count_leaves(v) for v in obj.values())
return 1
print(count_leaves(record[0]))
# 2
print(len(pd.json_normalize(record, sep="_").columns))
# 1When the two numbers differ for a single record, names have collided. Two fixes work:
- Choose a separator that appears in no key of your data.
"__"or"|"are common choices when keys use single underscores. - Keep the default
"."and rename columns afterwards, once the data is safely flattened. Collisions are only silent if you make them happen, and a separator that does not appear in your keys cannot cause one.
You can check the keys quickly before choosing. Collect the key names with a small recursive function and test whether the candidate separator occurs in any of them.
def all_keys(obj):
if isinstance(obj, dict):
for key, value in obj.items():
yield str(key)
yield from all_keys(value)
keys = set(all_keys(record[0]))
print(sorted(keys))
# ['address', 'address_city', 'city']
print(any("_" in key for key in keys))
# True
print(any("__" in key for key in keys))
# FalseHere "_" is unsafe for this record, but "__" is safe.
Renaming instead of changing `sep`
You do not have to decide the final names inside json_normalize. A common pattern is to flatten with the default and rename afterwards. This keeps the flatten step predictable, and you apply one naming policy in one place.
df = pd.json_normalize(users)
df.columns = df.columns.str.replace(".", "_", regex=False)
print(df.columns.tolist())
# ['id', 'name', 'address_city', 'address_geo_lat', 'address_geo_lng']Pass regex=False. In older pandas versions, str.replace treats "." as a regular expression that matches any character. That would turn every character into an underscore. Recent versions default to regex=False, but stating it makes the code correct on any version.
Renaming also lets you shorten names, which sep cannot do. For example, you can keep only the last segment of each path.
df = pd.json_normalize(users)
leaf_names = df.columns.str.split(".").str[-1]
print(leaf_names.tolist())
# ['id', 'name', 'city', 'lat', 'lng']Shortening can create duplicate names. If one record had home.city and another path had work.city, both would become city. Check with leaf_names.is_unique before you assign the result to df.columns. A DataFrame with duplicate column names is legal, but selecting df["city"] then returns two columns instead of one.
Summary of when each approach fits
- Use the default
"."when you are exploring data and want names that mirror the JSON structure. - Use
sep="_"orsep="__"when the columns will be used as identifiers in code, SQL, or another tool, and you have checked for collisions. - Rename afterwards when you need a policy that
sepcannot express, such as shortened names or a mix of styles.
Exercise
You call pd.json_normalize(data, sep="_") on a record {"a_b": 1, "a": {"b": 2}}. How many columns does the result have, and how can you avoid the problem?
Show answer
The result has one column, a_b, because the key a_b and the nested path a → b both produce the name a_b, and one value replaces the other. Avoid it by choosing a separator that does not occur in any key, such as "__", which gives the two columns a_b and a__b. You can also flatten with the default "." and rename afterwards.
Exercise
A DataFrame has the column address.city. Write one expression that selects the rows where that column equals "London", using query.
Show answer
df.query("address.city == 'London'"). The backticks tell query that the dot is part of the column name and not attribute access. With sep="_", you could write df.query("address_city == 'London'") without backticks.
Exercise
After flattening, you shorten every column to its last path segment with df.columns.str.split(".").str[-1]. What can go wrong, and how do you check for it before assigning the result?
Show answer
Different paths can end in the same key, such as home.city and work.city, which would both become city and leave duplicate column names. Check the new names with .is_unique before assigning them to df.columns.