🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpandas

pandas Documentation

LOADING ENGINE...

df.to_json()

AI & DATA SCIENCE // df-to-json

df.to_json() converts a DataFrame into a JSON string (or writes it directly to a file), with the orient parameter controlling the specific JSON structure produced.

Syntax

df.to_json(path_or_buf=None, orient='columns')

Deep Dive Course

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.

editor.html
import pandas as pd

df = pd.DataFrame({"name": ["Alice", "Bob"], "age": [30, 25]})
print(df.to_json(orient="records"))
localhost:3000

2Practical Example

Here is a real-world application of df.to_json() showing how it is used in production Pandas code.

editor.html
import pandas as pd

df = pd.DataFrame({"name": ["Alice", "Bob"], "age": [30, 25]})
print(df.to_json(orient="columns"))
localhost:3000

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.

editor.html
import pandas as pd

df = pd.DataFrame({"name": ["Alice", "Bob"], "age": [30, 25]})
print(df.to_json(orient="records"))
localhost:3000

Examples

Example 01Basic Usage
import pandas as pd

df = pd.DataFrame({"name": ["Alice", "Bob"], "age": [30, 25]})
print(df.to_json(orient="records"))
Example 02Advanced Example
import pandas as pd

df = pd.DataFrame({"name": ["Alice", "Bob"], "age": [30, 25]})
print(df.to_json(orient="columns"))

Best Practices

  • Use orient='records' for JSON intended for external consumption by another tool or API, since it's the most broadly compatible and expected shape
  • Leave path_or_buf unset when you need the JSON as an in-memory string rather than written directly to a file
  • 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

Interview Question

Why does the orient parameter matter so much when converting a DataFrame to JSON, given both 'records' and 'columns' represent the exact same underlying data?

Hint: Think about what shape a consumer of the JSON, like a JavaScript frontend, would actually expect.

Both orientations do represent exactly the same data, just structured completely differently, and most JSON-consuming tools or APIs expect a specific shape, most commonly a plain list of objects, matching orient='records', since that maps naturally onto how most programming languages iterate over collections of records. Producing the column-oriented default shape instead, when a consumer expects a list of row-objects, would require that consumer to write extra, non-obvious code just to reshape the data back into a usable form, which is exactly why picking the right orient explicitly for your specific use case matters.

Exercises

MediumPractice using df.to_json() in a real scenario.
View Solution
import pandas as pd

df = pd.DataFrame({"name": ["Alice", "Bob"], "age": [30, 25]})
print(df.to_json(orient="records"))

Frequently Asked Questions

Why does the orient parameter matter so much when converting a DataFrame to JSON, given both 'records' and 'columns' represent the exact same underlying data?

Both orientations do represent exactly the same data, just structured completely differently, and most JSON-consuming tools or APIs expect a specific shape, most commonly a plain list of objects, matching orient='records', since that maps naturally onto how most programming languages iterate over collections of records. Producing the column-oriented default shape instead, when a consumer expects a list of row-objects, would require that consumer to write extra, non-obvious code just to reshape the data back into a usable form, which is exactly why picking the right orient explicitly for your specific use case matters.

Related Functions

pd-read-jsondf-to-csvjson-module