← Back to Pandas Course | Chapter 11: File I/O | Lesson 3 of 7

read_json/to_json

JSON is the language of web APIs, and Pandas reads and writes it directly.

In this page:

  1. read_json/to_json
Syntax
python
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

python
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
  1. Choosing the wrong orient
  2. Deeply nested JSON not flattened
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.