Sub topic 3
Your first json_normalize call
This chapter assumes you know basic Python (dicts, lists, imports) and can create a pandas DataFrame and inspect its columns. You should also know that a JSON object becomes a Python dict and a JSON array becomes a list. If you have JSON as text, parse it first with json.loads. pd.json_normalize works on the resulting Python objects, not on raw strings.
What json_normalize does
pd.json_normalize takes a dict, or a list of dicts, and returns a DataFrame. Each input dict becomes one row. Each value that is not a nested dict becomes a column value. Each nested dict is flattened into extra columns, one per leaf value. A leaf is a value that is not a dict, such as a number, a string, or a list.
Compare this with pd.DataFrame(users). That call would keep the whole address dict inside a single cell. json_normalize unpacks it for you.
A first example
The input below is a list of two records. Each record 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']The result has two rows and five columns. The flat keys id and name keep their names. The nested keys get a dotted name that records the path from the top of the record to the leaf. The leaf lat sits under address and then geo, so its column is address.geo.lat.
Reading the result
Print the DataFrame to check the values, and use df.shape to confirm the row count. A quick check after any flattening is that the number of rows equals the number of input records. That holds here because we have not asked for lists to be expanded.
print(df.shape)
# (2, 5)
print(df.loc[0, "address.geo.lat"])
# 51.5Access a dotted column with square brackets and a string, as in df["address.city"]. Attribute access such as df.address.city does not work, because the dot is part of the column name.
Passing a single dict
You can also pass one dict instead of a list. You get a DataFrame with a single row.
single = pd.json_normalize(users[0])
print(single.shape)
# (1, 5)Common errors
- Passing a string.
pd.json_normalize('[{"id": 1}]')fails because the input is JSON text. Calljson.loadsfirst. - Passing a dict that wraps the records. Many APIs return
{"status": "ok", "data": [...]}. Passing that whole dict gives you one row. Passpayload["data"]instead, or userecord_path, which a later chapter covers. - Expecting lists to be flattened. Lists are left as they are. A later chapter explains why and how to expand them.
- Using
df.address.city. Usedf["address.city"]instead.
Exercise
Given data = [{"id": 7, "owner": {"name": "Lin", "contact": {"email": "[email protected]"}}}], what is the list of column names that pd.json_normalize(data) produces, and how many rows does the result have?
Show answer
The columns are ['id', 'owner.name', 'owner.contact.email'], and the result has one row, because the input list holds one record.
Exercise
A web API returns the Python dict payload = {"status": "ok", "users": [{"id": 1, "name": "Ada"}, {"id": 2, "name": "Grace"}]}. Which argument should you pass to pd.json_normalize to get a two-row DataFrame with columns id and name?
Show answer
Pass the inner list, pd.json_normalize(payload["users"]). Passing the whole payload would give a single row whose users column holds a list.