read_json/to_json
JSON is the language of web APIs, and Pandas reads and writes it directly.
In this page:
Syntax
df = pd.read_json("file.json")
df.to_json("out.json", orient="records")
read_json/to_json
read_json parses JSON text into a DataFrame, and to_json writes one. The orient argument controls the layout: "records" gives a list of row dicts, "columns" nests by column. For deeply nested JSON, pd.json_normalize flattens it.
Note:
orient="records" matches the typical API response shape.
Example: read_json/to_json
import io
import pandas as pd
js = '[{"name": "Ann", "age": 28}, {"name": "Bob", "age": 35}]'
df = pd.read_json(io.StringIO(js))
print(df)
print(df.to_json(orient="records"))
print(pd.json_normalize([{"a": 1, "b": {"c": 2}}]))
# Output:
# name age
# 0 Ann 28
# 1 Bob 35
# [{"name":"Ann","age":28},{"name":"Bob","age":35}]
# a b.c
# 0 1 2
Related Topics
Common Mistakes
- Choosing the wrong orient
- Deeply nested JSON not flattened
- Forgetting lines=True for JSON Lines files
Chapter Summary
- read_json and to_json handle JSON
- orient sets the layout
- records is a list of row dicts
- json_normalize flattens nesting
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: