Ravindra BagaleCourses & study guides मराठी Track your progress

26. How to Read APIs, JSON and Zipped CSVs into pandas

Data Science

26.3 JSON into a DataFrame

Why. JSON rarely arrives as a perfect rectangle. You need a clear path from nested dicts to columns.

What.

  • pd.DataFrame(list_of_dicts) when the payload is already a list of flat records.
  • pd.json_normalize(records) when records have nested dicts (customer.city).
  • pd.read_json(path_or_url) for JSON files that are tables or records.

How.

Normalize classroom payload

  1. json.loads or response.json().
  2. Find the list of records (often under a key like orders).
  3. pd.json_normalize(...) or DataFrame(...).
  4. head(), dtypes, shape.
  5. Rename columns to your course style (amount_inr, city).

Worked example A — List under orders.

import json
from pathlib import Path
import pandas as pd

payload = json.loads(Path("data/raw/status_sample.json").read_text(encoding="utf-8"))
df = pd.json_normalize(payload["orders"])
print(df.shape)
print(df)

Worked example B — Nested customer dict.

import pandas as pd

records = [
    {"order_id": "BLK-10", "amount_inr": 120, "customer": {"name": "Ruhi Bagale", "city": "Pune"}},
    {"order_id": "BLK-11", "amount_inr": 90, "customer": {"name": "Amir", "city": "Nashik"}},
]
df = pd.json_normalize(records)
print(df.columns.tolist())
print(df)

Worked example C — read_json records file.

from pathlib import Path
import pandas as pd

Path("data/raw/orders_records.json").write_text(
    '[{"order_id":"BLK-20","city":"Solapur","amount_inr":70},'
    '{"order_id":"BLK-21","city":"Nagpur","amount_inr":150}]',
    encoding="utf-8",
)
df = pd.read_json("data/raw/orders_records.json")
print(df)

Ravindra Bagale's Tip

First find the key that holds the list of records, such as orders, and print one raw record to see how it is nested. Then pass only that list to pd.json_normalize() and check shape and head(). Do not print the whole JSON in one cell, because a long wall of text hides the structure and wastes time.