Sub topic 1
What Nested JSON Looks Like and Why It Needs Flattening
Most web APIs and document stores return JSON, and most analysis tools expect a table. This chapter shows the shapes nested JSON takes and what goes wrong when you load it into a DataFrame unchanged. It also explains what "flattening" has to accomplish. The later chapters introduce pd.json_normalize and its parameters.
Prerequisites
This chapter assumes you already know:
- Basic Python: dictionaries, lists, loops, and importing modules.
- Basic pandas: creating a DataFrame, reading
df.columns,df.shape, anddf.dtypes. - What JSON is, and that its objects and arrays become Python dicts and lists when parsed.
You need pandas installed (pip install pandas). Every code block below runs on its own.
Why a table and nested JSON disagree
A DataFrame is rectangular. Every row has the same columns, and every cell holds one value. JSON has no such constraint. An object can contain objects, an array can hold any number of elements, and two objects in the same array can have different keys.
Flattening means turning a tree of values into rows and columns so that each field you care about has its own column. You usually want this because the table operations you rely on need single values in cells:
- Filtering such as
df[df["city"] == "London"]. groupbyand aggregation.mergewith other tables.- Export with
to_csvorto_sql. - Numeric work, which needs numeric dtypes rather than
objectcolumns holding dicts.
The three shapes of nesting
Nested JSON is built from a few patterns. Each one calls for a different flattening move, so learn to tell them apart.
Nested objects
An object inside an object. Each parent has exactly one child, so the relationship is one to one. Flattening turns each leaf value into a column. The parent contributes no extra rows.
{"id": 1, "name": "Ada", "address": {"city": "London", "geo": {"lat": 51.5, "lng": -0.12}}}Arrays of scalars
An array whose elements are plain values such as strings or numbers.
{"id": 1, "title": "Intro", "tags": ["python", "pandas"]}There is no single obvious table for this. You could make one column per position, one row per tag, or keep the list in one cell. The right choice depends on the question you are asking.
Arrays of records
An array whose elements are objects with their own keys. Here the relationship is one to many: one order has many line items.
{"order_id": 100, "items": [{"sku": "A1", "qty": 2}, {"sku": "B2", "qty": 1}]}Flattening this means choosing a row grain. The grain is what one row represents. You can keep one row per order, which leaves the items packed in a cell, or use one row per item, which repeats the order fields on each row.
Real documents mix all three. The following table summarizes how JSON constructs map to Python and to the flattening decision.
| JSON construct | Python type after `json.loads` | Flattening decision |
|---|---|---|
| Object inside an object | `dict` | Becomes more columns, one per leaf value |
| Array of numbers or strings | `list` of scalars | Keep as a list in a cell, or expand it yourself |
| Array of objects | `list` of `dict` | Expand to one row per element, or keep as a list |
| `null` | `None` | Becomes a missing value |
| Key absent from some objects | no entry in the `dict` | Becomes a missing value in that row |
Reading the shape of a document
Before you flatten anything, find out what shape you have. The helper below walks a parsed document and reports each object, array of records, and array of scalars with its path.
def describe(value, path="$", depth=0):
indent = " " * depth
if isinstance(value, dict):
print(f"{indent}{path}: object with keys {list(value)}")
for key, child in value.items():
describe(child, f"{path}.{key}", depth + 1)
elif isinstance(value, list):
if value and all(isinstance(v, dict) for v in value):
print(f"{indent}{path}: array of {len(value)} records")
describe(value[0], f"{path}[0]", depth + 1)
else:
print(f"{indent}{path}: array of {len(value)} values")
else:
print(f"{indent}{path}: {type(value).__name__}")
order = {
"order_id": 100,
"customer": {"id": 1, "name": "Ada"},
"tags": ["gift", "rush"],
"items": [{"sku": "A1", "qty": 2}, {"sku": "B2", "qty": 1}],
}
describe(order)
# $: object with keys ['order_id', 'customer', 'tags', 'items']
# $.order_id: int
# $.customer: object with keys ['id', 'name']
# $.customer.id: int
# $.customer.name: str
# $.tags: array of 2 values
# $.items: array of 2 records
# $.items[0]: object with keys ['sku', 'qty']
# $.items[0].sku: str
# $.items[0].qty: intThe helper inspects only the first record of each array, so it can miss keys that appear in later records. Treat its output as a first look rather than a schema.
The structure also decides what you do next. This document has one object to merge into columns (customer), one array of scalars (tags), and one array of records (items). Each needs a separate decision.
What happens without flattening
The obvious first attempt is to pass the parsed data to pd.DataFrame. It works without error, but nested values are not flattened.
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.DataFrame(users)
print(df.columns.tolist())
# ['id', 'name', 'address']
print(df["address"].iloc[0])
# {'city': 'London', 'geo': {'lat': 51.5, 'lng': -0.12}}
print(df["address"].dtype)
# objectThe address column holds whole dicts, so there is no city column. You can reach into one key with df["address"].str["city"], but you would repeat that for every nested field, and it breaks when a row has None instead of a dict. Methods like groupby("city") and numeric operations on latitude have nothing to work on.
Arrays of records behave differently, and the effect is easy to miss.
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.shape)
# (2, 3)
print(df["items"].iloc[0])
# [{'sku': 'A1', 'qty': 2}, {'sku': 'B2', 'qty': 1}]
print(sum(len(o["items"]) for o in orders))
# 3The frame has 2 rows, one per order, but the data contains 3 line items. Any question about items, such as total quantity per SKU, cannot be answered from this table. The items cell is a Python list, and pandas treats it as an opaque object.
Row grain changes the row count
Nested objects change only the number of columns. Arrays of records change the number of rows, so they are the part of flattening that needs the most care.
- One to one (nested objects): the row count stays the same.
- One to many (arrays of records): expanding the array gives one row per element, so the count grows. In the order example it goes from 2 to 3.
- Parent fields repeat: after expansion,
order_idappears on every item row. Summing an order-level value, such as a shipping fee, across item rows counts it once per item. - Empty arrays: a parent whose array is empty contributes zero rows when the array is expanded, so that parent vanishes from the result.
Decide the grain before you write any code. Ask what one row of the final table should mean: one user, one order, or one line item.
Messy inputs to expect
Real data breaks the tidy examples above in a few common ways:
- Optional keys. One record has
coupon, another does not. After flattening, the missing key becomes a missing value in that row. - Inconsistent types. A key holds an object in one record and
nullor a string in another. Code that assumes a dict will fail on the others. - Wrapper objects. APIs often return
{"status": "ok", "data": [ ... ]}instead of a bare array. The list you want sits under a key, and you must select it first. - Keys containing dots. A key such as
"a.b"will later produce column names that look like nested paths. This makes dotted names ambiguous. - Variable depth. Some records nest three levels deep and others one. The flattened frame then has columns that are mostly empty.
Where this leads
The next chapters cover loading JSON text with json.loads and then flattening with pd.json_normalize. In short, json_normalize handles nested objects by creating one column per leaf value. It handles arrays of records through a separate pair of arguments that choose which array to expand and which parent fields to keep. Arrays of scalars stay as lists unless you expand them yourself.
Exercise
Given the document {"id": 7, "owner": {"name": "Lin"}, "labels": ["a", "b", "c"], "events": [{"t": 1}, {"t": 2}]}, which keys are a nested object, an array of scalars, and an array of records? If you wanted one row per event, how many rows would this single document produce?
Show answer
"owner" is a nested object, "labels" is an array of scalars, and "events" is an array of records. One row per event gives 2 rows, and each would repeat the parent fields such as id 7.
Exercise
A colleague loads a list of 500 orders with pd.DataFrame(orders) and reports "500 rows, so we have 500 line items." What is wrong with this conclusion, and what should they check?
Show answer
Each row is one order, not one line item, because the items array stays as a list in a single cell. The number of line items is the sum of len(order["items"]) over all orders, which can be larger than 500 (or smaller, if some arrays are empty). They should inspect the items column and decide on the row grain before counting.