Pandas Read JSON
JSON (JavaScript Object Notation) is the language of web APIs and many configuration files. Unlike CSV it can nest data, so it maps to a table in more than one way. pandas reads it with pd.read_json(), and flattens nested records with pd.json_normalize().
Reading JSON
As with CSV, real code passes a path or URL:
import pandas as pd
df = pd.read_json("products.json")
df = pd.read_json("https://api.example.com/products")In the playgrounds we wrap the JSON text in io.StringIO. (Passing a raw JSON string directly to read_json is deprecated in pandas 2, so StringIO is the right habit anyway.)
A list of records
The most common JSON shape is a list of objects, one object per row. pandas turns each key into a column:
import io
import pandas as pd
text = """[
{"sku": "TEA-01", "name": "Green tea", "price": 4.5, "in_stock": true},
{"sku": "TEA-02", "name": "Black tea", "price": 3.9, "in_stock": false},
{"sku": "COF-01", "name": "Espresso", "price": 7.25, "in_stock": true}
]"""
products = pd.read_json(io.StringIO(text))
print(products)
print(products.dtypes) sku name price in_stock
0 TEA-01 Green tea 4.50 True
1 TEA-02 Black tea 3.90 False
2 COF-01 Espresso 7.25 True
sku object
name object
price float64
in_stock bool
dtype: object
JSON true/false became the bool dtype, and numbers became float64.
Other orientations
JSON can also store a table as a dictionary of columns. The orient parameter tells pandas which layout to expect:
orient |
JSON shape |
|---|---|
"records" |
[{"col": value, ...}, ...] |
"columns" (default for objects) |
{"col": {"row": value, ...}, ...} |
"index" |
{"row": {"col": value, ...}, ...} |
"split" |
{"index": [...], "columns": [...], "data": [[...], ...]} |
"values" |
[[...], [...]], just the data |
import io
import pandas as pd
by_index = """{
"Lisbon": {"country": "Portugal", "sunny_days": 259},
"Bergen": {"country": "Norway", "sunny_days": 89},
"Seville": {"country": "Spain", "sunny_days": 300}
}"""
cities = pd.read_json(io.StringIO(by_index), orient="index")
print(cities) country sunny_days
Lisbon Portugal 259
Bergen Norway 89
Seville Spain 300
With orient="index", the outer keys become the row labels.
Missing keys
Records do not all need the same keys. Missing fields simply become missing values:
import io
import pandas as pd
text = """[
{"user": "mia", "age": 31, "city": "Porto"},
{"user": "raj", "city": "Pune"},
{"user": "ola", "age": 27}
]"""
users = pd.read_json(io.StringIO(text))
print(users) user age city
0 mia 31.0 Porto
1 raj NaN Pune
2 ola 27.0 NaN
Nested JSON with json_normalize
API responses often nest objects inside objects. read_json would leave the inner object as a dictionary in one cell; pd.json_normalize() flattens it into dotted column names. It takes already-parsed Python data, so we first use the standard json module:
import json
import pandas as pd
response = """[
{"id": 1, "customer": {"name": "Ana", "tier": "gold"}, "total": 120.0},
{"id": 2, "customer": {"name": "Ben", "tier": "basic"}, "total": 35.5},
{"id": 3, "customer": {"name": "Cy", "tier": "gold"}, "total": 88.0}
]"""
orders = pd.json_normalize(json.loads(response))
print(orders)
print(orders.groupby("customer.tier")["total"].sum()) id total customer.name customer.tier
0 1 120.0 Ana gold
1 2 35.5 Ben basic
2 3 88.0 Cy gold
customer.tier
basic 35.5
gold 208.0
Name: total, dtype: float64
When each record holds a list of children (for example the lines of an order), record_path creates one row per child, and meta copies fields from the parent:
import json
import pandas as pd
data = json.loads("""[
{"order": "A1", "lines": [{"item": "pen", "qty": 3}, {"item": "ink", "qty": 1}]},
{"order": "B2", "lines": [{"item": "pad", "qty": 2}]}
]""")
lines = pd.json_normalize(data, record_path="lines", meta=["order"])
print(lines) item qty order
0 pen 3 A1
1 ink 1 A1
2 pad 2 B2
Note: If a JSON file has one object per line (common for logs), read it with
pd.read_json(path, lines=True).
Test yourself
Which JSON shape is a list with one object per row?
- orient="split"
- orient="records"
- orient="index"
- orient="values"
What does pd.json_normalize do with {"customer": {"name": "Ana"}}?
- Drops the nested object
- Creates a column called
customer.name - Raises an error
- Stores the dictionary in a single cell
A record is missing the key age that other records have. What does pandas put in that cell?
- 0
- An empty string
- A missing value (NaN)
- It drops the record