Sub topic 1
What nested JSON looks like and why it needs flattening
Prerequisites
This chapter assumes you know three things:
- Basic Python: dictionaries, lists, and importing modules.
- Basic pandas: creating a DataFrame and inspecting its columns.
- How JSON maps to Python. A JSON object becomes a
dict, and a JSON array becomes alist.
Why tables and JSON do not fit together
A DataFrame is a flat grid. Every row has the same columns, and each cell normally holds one simple value such as a number or a string.
JSON has no such limit. A value can be another object, or an array of objects, to any depth. APIs return this shape because it mirrors how the data is stored. Web APIs, log files, and document databases all produce it.
When you load nested JSON into a DataFrame directly, the nesting survives inside the cells. You get a table that still hides most of its data.
The two kinds of nesting
Two shapes cause nearly all the trouble. Learn to tell them apart, because the next chapters treat them differently.
- A nested object. A key whose value is another object, such as
"customer": {"id": 1, "name": "Ada"}. Each customer has exactly one such object, so it fits in the same row. Flattening means promoting its fields to columns of their own. - A list of records. A key whose value is an array of objects, such as
"items": [{...}, {...}]. One order can hold any number of items, so these do not fit in one row. Flattening means giving each element its own row.
A third case also exists: a list of plain values such as ["python", "pandas"]. A later chapter covers it.
Here is one order document that contains the first two shapes.
order = {
"order_id": 100,
"customer": {"id": 1, "name": "Ada"},
"items": [
{"sku": "A1", "qty": 2},
{"sku": "B2", "qty": 1},
],
}The diagram shows the same document as a tree.
Plain fields such as order_id already fit a column. The customer branch is the nested object, and the items branch is the list of records.
What goes wrong without flattening
Pass a list of such documents to the DataFrame constructor and see what you get.
import pandas as pd
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}],
},
]
df = pd.DataFrame(orders)
print(df.columns.tolist())
# ['order_id', 'customer', 'items']
print(df["customer"].iloc[0])
# {'id': 1, 'name': 'Ada'}
print(type(df["items"].iloc[0]))
# <class 'list'>Only the top-level keys became columns. The customer column holds whole dicts, and the items column holds whole lists.
This causes practical problems:
- You cannot filter on
customer.namewith a normal column expression. groupbyandmergecannot use values hidden inside dicts.- Summing
qtyacross all orders is impossible without looping over the lists yourself. - Writing to CSV or a database stores the dicts and lists as text.
The goal of flattening is a table where every value you care about sits in its own column, with one row per record.
What flattening produces
For the orders above, the useful target is one row per item, with the customer's name and the order id repeated on each row:
| sku | qty | order_id | customer name |
|---|---|---|---|
| A1 | 2 | 100 | Ada |
| B2 | 1 | 100 | Ada |
| A1 | 5 | 101 | Grace |
Two orders became three rows, because order 100 has two items. The nested object became a column. The list of records became rows, and the parent fields were copied onto each row.
pandas.json_normalize performs this transformation. The rest of this tutorial builds up its options one at a time. First you will load JSON text into Python, then flatten nested objects, and later expand lists into rows.
Exercise
A JSON document has the key "address" holding {"city": "London", "zip": "N1"} and the key "phones" holding [{"type": "home", "number": "123"}, {"type": "work", "number": "456"}]. Which key is a nested object, which is a list of records, and which one would add rows when flattened?
Show answer
"address" is a nested object, because each record has exactly one. Its fields become columns. "phones" is a list of records, because a person can have any number of them. Expanding it creates one row per phone.