Sub topic 2
Getting JSON into Python
This chapter assumes you know Python dictionaries and lists, can create a DataFrame and inspect its columns, and know what a JSON object and array look like. It covers the step before pd.json_normalize: turning JSON text, a file, or an API response into the Python objects that function accepts. Most "flattening" problems that look like pandas bugs start here, when the data isn't the shape you assumed.
What json_normalize expects
pd.json_normalize does not read text. It takes Python objects: a dictionary, or a list of dictionaries. JSON arrives as text (a str or bytes) in files, HTTP responses, and message queues. You first parse that text with Python's standard json module, then pass the result on.
The path has three stages: get the text, parse it into dicts and lists, then flatten.
How JSON types map to Python types
The json module converts each JSON type to a fixed Python type.
| JSON | Python |
|---|---|
| object | `dict` |
| array | `list` |
| string | `str` |
| number without a fraction or exponent | `int` |
| number with a fraction or exponent | `float` |
| `true` / `false` | `True` / `False` |
| `null` | `None` |
Two details matter later. First, null becomes None, not NaN. A None stays in a column as a missing value, and pandas may convert it to NaN depending on the column's other values. Second, the parser keeps numbers as JSON wrote them. A value written as "51.5" (in quotes) is a string and stays a string, which is why the cleanup chapter converts dtypes after flattening.
Parsing a string with json.loads
json.loads ("load string") takes JSON text and returns Python objects. The following script parses a small response, then prints an outline of its structure. The outline helper is useful whenever you meet an unfamiliar document.
import json
text = """
{
"status": "ok",
"count": 2,
"results": [
{"id": 1, "name": "Ada", "active": true, "nickname": null},
{"id": 2, "name": "Grace", "active": false, "nickname": null}
]
}
"""
data = json.loads(text)
print(type(data))
# <class 'dict'>
print(data["results"][0]["active"])
# True
def outline(value, indent=0):
pad = " " * indent
if isinstance(value, dict):
for key, child in value.items():
print(f"{pad}{key}: {type(child).__name__}")
outline(child, indent + 1)
elif isinstance(value, list) and value:
print(f"{pad}[0] of {len(value)}: {type(value[0]).__name__}")
outline(value[0], indent + 1)
outline(data)
# status: str
# count: int
# results: list
# [0] of 2: dict
# id: int
# name: str
# active: bool
# nickname: NoneTypeThe outline shows the document's real shape. The top level is an object that holds metadata (status, count) and a list of records under results. The helper inspects only the first element of each list, so it can miss keys that appear in later records. Treat it as a first look, not a schema.
json.loads accepts str, bytes, and bytearray. Passing bytes is convenient when you read a network body, because the function detects UTF-8, UTF-16, or UTF-32 itself.
Reading a file with json.load
json.load (no s) reads from an open file object. Open the file with an explicit encoding, because the default depends on the operating system.
import json
import tempfile
from pathlib import Path
users = [
{"id": 1, "name": "Ada", "address": {"city": "London"}},
{"id": 2, "name": "Grace", "address": {"city": "New York"}},
]
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "users.json"
path.write_text(json.dumps(users), encoding="utf-8")
with path.open(encoding="utf-8") as f:
loaded = json.load(f)
print(loaded == users)
# Truejson.dumps is the reverse direction: it turns Python objects into JSON text. The example uses it to create a file, and the round trip returns an equal list. The temporary folder keeps the example from leaving files behind.
Passing the result to json_normalize
Once you hold Python objects, the next step depends on the top-level shape.
- A list of dicts: pass it directly.
- A single dict that represents one record: pass it directly and you get a one-row DataFrame.
- A dict that wraps a list of records, as in the
resultsexample above: pass the inner list.
import pandas as pd
df = pd.json_normalize(data["results"])
print(df.columns.tolist())
# ['id', 'name', 'active', 'nickname']
print(len(df))
# 2If you pass the whole data dict instead, you get a single row with columns status, count, and results, where results holds the entire list in one cell. That is the "list stays as a list" behavior covered later in this tutorial. Nothing fails, and the table is simply not what you wanted. Checking the shape first avoids that.
Newline-delimited JSON
Some exports and logs use JSON Lines: one complete JSON object per line, with no surrounding array. json.loads cannot parse the whole text at once, because the document as a whole is not valid JSON. Parse it line by line.
import json
import pandas as pd
lines = '{"id": 1, "tags": ["a"]}\n{"id": 2, "tags": []}\n'
records = [json.loads(line) for line in lines.splitlines() if line.strip()]
df = pd.json_normalize(records)
print(df.columns.tolist())
# ['id', 'tags']The if line.strip() guard skips blank lines, such as the empty one after a trailing newline. Without it, json.loads("") raises an error.
Common errors
Most failures at this stage fall into four groups.
- The text is not valid JSON. Python's
jsonmodule follows the standard, which is stricter than Python syntax. Single quotes, trailing commas, comments, andTrueorNoneare all rejected. The error isjson.JSONDecodeError, a subclass ofValueError, and it reports where parsing stopped. - The input is already parsed.
requestsresponses expose.json(), which returns Python objects. Callingjson.loadson that result raisesTypeError, because it expects text, not a dict. - The file has more than one document. JSON Lines files, or two arrays pasted together, raise
JSONDecodeErrorwith the message "Extra data". - The top level is not what you assumed. A response that is sometimes a list and sometimes a dict (for example an error object) passes parsing and then fails or misbehaves later.
The following script reproduces the first two errors and shows how to read the details.
import json
bad_text = "{'id': 1}" # a Python-style literal, not JSON
try:
json.loads(bad_text)
except json.JSONDecodeError as err:
print(err.msg)
print(err.lineno, err.colno)
# Expecting property name enclosed in double quotes
# 1 2
already_parsed = {"id": 1}
try:
json.loads(already_parsed)
except TypeError as err:
print(err)
# the JSON object must be str, bytes or bytearray, not dictThe lineno and colno attributes point at the offending character. In a long file, they save you from searching by eye.
Defensive checks before flattening
A few lines of validation turn confusing downstream behavior into a clear message. These checks are cheap, and they matter most when the data comes from an API you do not control.
import json
import pandas as pd
def load_records(text, key=None):
data = json.loads(text)
if key is not None:
data = data[key]
if isinstance(data, dict):
data = [data]
if not isinstance(data, list):
raise TypeError(f"expected a list of records, got {type(data).__name__}")
return pd.json_normalize(data)
df = load_records('{"results": [{"id": 1}, {"id": 2}]}', key="results")
print(df["id"].tolist())
# [1, 2]
df_single = load_records('{"id": 7, "name": "Ada"}')
print(len(df_single))
# 1The function selects an optional envelope key, wraps a single dict into a one-element list, and rejects anything else with a clear error. It does not check that every element of the list is a dict. If an element is something else, such as a string, json_normalize fails, and that is a data problem worth surfacing.
Number precision and parse hooks
Python integers have no size limit, so json.loads keeps large integers exactly. Floats are ordinary 64-bit floats, so a number such as 0.1 carries the usual binary rounding. If you need exact decimal values (money, for instance), pass parse_float=decimal.Decimal to json.loads. The resulting columns then hold Decimal objects with dtype object, which pandas handles, though arithmetic is slower than with float64. For most analysis, plain floats are fine.
A note on pd.read_json
pd.read_json parses JSON and builds a DataFrame in one call. It works well when the JSON is already table-like, such as a list of flat objects. It does not flatten nested objects into dotted columns, and it has no record_path or meta. Parsing with json first and flattening with json_normalize gives you a chance to inspect and select the data in between, which is why this tutorial uses that route. The last chapter compares the two in more detail.
Exercise
An API client returns the text [{"id": 1, "owner": {"name": "Ada"}}, {"id": 2, "owner": {"name": "Grace"}}]. Write the two lines of Python that produce a DataFrame, and name the column that holds the owner name.
Show answer
Parse with data = json.loads(text) and flatten with df = pd.json_normalize(data). The owner name column is owner.name, because the nested key path is joined with a dot. (id is the other column.)
Exercise
A colleague reads a response with resp.json() and then calls json.loads on the result. It raises TypeError. Why, and what is the fix?
Show answer
resp.json() already parsed the body into Python objects, so the result is a dict or list. json.loads accepts only str, bytes, or bytearray. Remove the json.loads call and pass the result of resp.json() straight to pd.json_normalize (after selecting an inner list if the records are wrapped).
Exercise
You load a file containing two lines, {"id": 1} and {"id": 2}, with json.load and get JSONDecodeError: Extra data. What format is the file, and how do you load it?
Show answer
It is JSON Lines: one JSON object per line, with no enclosing array. Read the lines and parse each one: records = [json.loads(line) for line in text.splitlines() if line.strip()], then call pd.json_normalize(records).