Sub topic 2
Getting JSON into Python
This chapter assumes you know basic Python dictionaries and lists and can create a pandas DataFrame. It covers the step before flattening: turning JSON text into Python objects that pd.json_normalize can accept.
JSON text versus Python objects
JSON is text. json_normalize does not read text. It reads Python dictionaries and lists. The standard library json module converts between the two, and the conversion follows fixed rules.
| JSON | Python |
|---|---|
| object `{}` | `dict` |
| array `[]` | `list` |
| string | `str` |
| number | `int` or `float` |
| `true` / `false` | `True` / `False` |
| `null` | `None` |
Parsing a string with json.loads
json.loads takes a string and returns the matching Python object. The "s" stands for string.
import json
text = '{"id": 1, "name": "Ada", "active": true, "manager": null, "tags": ["a", "b"], "score": 9.5}'
data = json.loads(text)
print(type(data).__name__)
for key, value in data.items():
print(key, type(value).__name__)
# dict
# id int
# name str
# active bool
# manager NoneType
# tags list
# score floatNotice that null becomes None. Later chapters show how missing values end up as NaN in a DataFrame.
Reading a file with json.load
json.load has no "s". It takes an open file object, not a path and not a string. The next example writes a small file first so you can run it as is. It also shows a common API shape, where the records sit under one key of a wrapper object.
import json
from pathlib import Path
import pandas as pd
path = Path("users.json")
path.write_text(
'{"count": 2, "results": ['
'{"id": 1, "address": {"city": "London"}}, '
'{"id": 2, "address": {"city": "New York"}}]}',
encoding="utf-8",
)
with path.open(encoding="utf-8") as f:
payload = json.load(f)
print(list(payload.keys()))
# ['count', 'results']
df = pd.json_normalize(payload["results"])
print(df.columns.tolist())
# ['id', 'address.city']The top level of payload is a dict with a count field and a results list. Passing payload directly would treat count and results as columns of a single row. Passing payload["results"] gives one row per user. Before you flatten, print the top-level keys and decide which part holds the records you want.
A response from the requests library works the same way. response.json() returns the parsed dict or list, so you do not call json.loads yourself.
Common errors
- Passing a string to
json_normalize. A string is not a dict or a list of dicts, so the call fails. Runjson.loadsfirst. - Mixing up
loadandloads.json.loads(open(...))andjson.load("text")both fail.loadstakes a string.loadtakes a file object. - Invalid JSON. JSON requires double quotes. Single quotes, trailing commas, and Python literals such as
TrueorNoneare not valid.
import json
try:
json.loads("{'id': 1}")
except json.JSONDecodeError as e:
print(type(e).__name__)
# JSONDecodeErrorA string that looks like a dict when you print it is not necessarily JSON. If it was produced by print(some_dict), it uses single quotes and will not parse.
Exercise
A file orders.json contains {"page": 1, "data": [{"order_id": 1}, {"order_id": 2}]}. Write the code that loads it with json.load and builds a DataFrame with one row per order.
Show answer
with open("orders.json", encoding="utf-8") as f:
payload = json.load(f)
df = pd.json_normalize(payload["data"])
The records are in the data list, so you pass payload["data"]. Passing payload would make a single row with page and data columns.