The orient parameter fundamentally changes the shape of the resulting JSON: 'records' produces a list of objects, one per row, which is the most common and generally most interoperable format for APIs and other tools; 'columns', the default, instead produces a dict mapping each column name to a dict of index-value pairs; other options like 'split', 'index', and 'table' offer further structural variations for specific use cases. Leaving path_or_buf as None returns the JSON as a string directly, rather than writing it to a file.
1Understanding df.to_json()
The orient parameter fundamentally changes the shape of the resulting JSON: 'records' produces a list of objects, one per row, which is the most common and generally most interoperable format for APIs and other tools; 'columns', the default, instead produces a dict mapping each column name to a dict of index-value pairs; other options like 'split', 'index', and 'table' offer further structural variations for specific use cases. Leaving path_or_buf as None returns the JSON as a string directly, rather than writing it to a file.
Pass orient='records' when producing JSON meant for another application or API to consume — it's the most widely expected and interoperable shape, a plain list of row-objects, compared to the column-oriented default.
import pandas as pd
df = pd.DataFrame({"name": ["Alice", "Bob"], "age": [30, 25]})
print(df.to_json(orient="records"))2Practical Example
Here is a real-world application of df.to_json() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"name": ["Alice", "Bob"], "age": [30, 25]})
print(df.to_json(orient="columns"))3Best Practices
Follow these guidelines when working with df.to_json():
1. Use orient='records' for JSON intended for external consumption by another tool or API, since it's the most broadly compatible and expected shape
2. Leave path_or_buf unset when you need the JSON as an in-memory string rather than written directly to a file
3. Verify how dates/timestamps are serialized, since to_json() has specific date_format options and JSON has no native date type, so the default representation may not match what a downstream consumer expects
Tip: Pass orient='records' when producing JSON meant for another application or API to consume — it's the most widely expected and interoperable shape, a plain list of row-objects, compared to the column-oriented default.
import pandas as pd
df = pd.DataFrame({"name": ["Alice", "Bob"], "age": [30, 25]})
print(df.to_json(orient="records"))