Sub topic 3
Your first json_normalize call
This chapter assumes you know Python dictionaries and lists, can create a pandas DataFrame and inspect its columns, and know how JSON objects and arrays map to Python dicts and lists. You will make a first pd.json_normalize call and learn what it accepts, what it returns, and how to read the result.
What json_normalize does
pd.json_normalize takes Python data that came from JSON and returns a DataFrame. Nested objects become extra columns, so the output has one row per input record and no dictionaries inside cells. The function is available as pd.json_normalize in pandas 1.0 and later. Older code may import it from pandas.io.json.
The function takes Python objects, not JSON text. If you hold a JSON string, parse it with json.loads first, as the previous chapter showed.
A first example
Here are two user records. Each has an address object, and that object contains a geo object.
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.shape)
# (2, 5)The result has two rows, one per user, and five columns. The input has two scalar keys at the top (id and name) and three leaf values inside address. A leaf value is a value that is not a dict, such as a number, string, boolean, None, or a list.
Each leaf becomes a column. The name is the path of keys from the top of the record to that leaf, joined with dots. The lat value is reached through address, then geo, then lat, so its column is address.geo.lat. You can read the values like any other column:
print(df.loc[0, "address.geo.lat"])
# 51.5
print(df["address.geo.lat"].dtype)
# float64Because the values are now plain columns, pandas assigns normal dtypes to them. The lat column is float64, so you can sort, filter, and aggregate it right away.
Compare with pd.DataFrame
It helps to see what the constructor does with the same data.
raw = pd.DataFrame(users)
print(raw.columns.tolist())
# ['id', 'name', 'address']
print(raw["address"].iloc[0])
# {'city': 'London', 'geo': {'lat': 51.5, 'lng': -0.12}}pd.DataFrame treats each top-level key as a column and leaves the whole address dict in a single cell. You can't filter on address by city without writing a Python function over the column. json_normalize does the walk for you and leaves one value per cell.
| Aspect | `pd.DataFrame(records)` | `pd.json_normalize(records)` |
|---|---|---|
| Columns | One per top-level key | One per leaf value |
| Nested dicts | Stay as dict objects in cells | Expanded into dotted column names |
| Column names | Original keys | Key paths joined with `.` |
| Typical dtype of nested numbers | `object` | `int64` or `float64` |
What you can pass in
The data argument accepts three kinds of input.
- A list of dicts. This is the usual case, and each dict becomes one row.
- A single dict. It is treated as a list with one record and gives a one-row DataFrame.
- Another iterable of dicts, such as a generator. It is converted to a list first.
Here is the single-dict case, using the first user from before:
one = pd.json_normalize(users[0])
print(one.shape)
# (1, 5)Two edge cases come up often. An empty list returns an empty DataFrame, so a response with zero results does not raise an error. A plain string raises an error, because the function does not parse JSON text.
print(pd.json_normalize([]).shape)
# (0, 0)The index and column order
The output always has a fresh RangeIndex starting at 0. If your input records carry an ID, it becomes an ordinary column like any other. Call df.set_index("id") yourself if you want it as the index.
Columns appear in the order that keys are first encountered. pandas processes the records in order and adds a column when it sees a key path for the first time. For records with identical shapes, the column order matches the key order in the first record. If a later record has an extra key, that column is added at the end. The next chapters cover what happens to records that lack a key.
Reading the result
After a first call, it helps to check the result before you build on it. Four quick checks cover most problems.
print(df.shape) # rows should equal the number of records
print(df.columns.tolist()) # are all the paths you expect there?
print(df.dtypes) # did numbers stay numeric?
print(df.head()) # eyeball a few rowsIf the row count is not what you expected, the input is probably not shaped the way you assumed. The most common cause is a response that wraps its records in an envelope.
Wrapped payloads
Many APIs return an object that holds metadata alongside a list of records:
payload = {
"count": 2,
"results": [
{"id": 1, "name": "Ada", "address": {"city": "London"}},
{"id": 2, "name": "Grace", "address": {"city": "New York"}},
],
}
wrong = pd.json_normalize(payload)
print(wrong.shape)
# (1, 2)
print(wrong.columns.tolist())
# ['count', 'results']
right = pd.json_normalize(payload["results"])
print(right.shape)
# (2, 3)
print(right.columns.tolist())
# ['id', 'name', 'address.city']Passing the whole payload treats it as one record. That gives one row, and results stays as a list inside a cell. Pass the list itself, payload["results"], to get one row per record. The record_path argument, which a later chapter covers, does the same selection and can also carry fields like count along.
Gotchas to know early
The following points can surprise you on the first real dataset.
- Lists are not expanded. If a record contains a list, such as
"tags": ["a", "b"], the column holds the Python list as a value. Only dicts are flattened. Turning lists into rows is the job ofrecord_path. - Every element must be a dict. A list such as
[1, 2, 3]or a list mixing dicts and numbers fails. Convert such data with a different tool, for instancepd.DataFrame({"value": values}). - Dots in original keys are ambiguous. A key that already contains a dot, like
"a.b", produces a column nameda.b, the same name a nested{"a": {"b": ...}}would produce. If both appear in the data, the columns collide. Choose a different separator when that is possible. - Key order matters for column order only. Records do not need identical keys, but differences are filled with
NaN. The chapter on missing keys covers this. - The input is not changed.
json_normalizereads your data and builds a new DataFrame. The original Python structure is left as it was.
A complete small script
This script starts from JSON text and shows the whole path from parsing to a filtered result.
import json
import pandas as pd
text = """
[
{"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}}}
]
"""
data = json.loads(text)
df = pd.json_normalize(data)
northern = df[df["address.geo.lat"] > 45]
print(northern["name"].tolist())
# ['Ada']The filter works directly on a nested value because json_normalize turned it into a numeric column. With pd.DataFrame(data) you would first need to extract the latitude from each dict in the address column.
Summary
pd.json_normalizeconverts a dict or a list of dicts into a DataFrame, with one row per record.- Each leaf value becomes a column, named by joining its key path with dots.
- Only dicts are flattened. Lists stay as values in cells.
- Wrapped payloads need the inner list passed in, or
record_path. - Always check the shape and column names after the first call.
Exercise
Given data = {"status": "ok", "items": [{"id": 1, "owner": {"name": "Ada"}}, {"id": 2, "owner": {"name": "Grace"}}]}, which call gives a two-row DataFrame, and what are its column names?
Show answer
Call pd.json_normalize(data["items"]). The columns are ['id', 'owner.name']. Calling pd.json_normalize(data) would give one row with the columns status and items, with the whole list stored in one cell.
Exercise
Why does pd.json_normalize produce a numeric address.geo.lat column while pd.DataFrame(users) leaves the latitude hidden in an address column of dicts?
Show answer
pd.DataFrame makes one column per top-level key and stores each nested dict as a single Python object in a cell. json_normalize walks every nested dict and creates one column per leaf value. The latitude is then a column of floats, so pandas gives it a float64 dtype and you can filter and aggregate it directly.