Exporting Pandas DataFrame to JSON File (original) (raw)

Last Updated : 25 Mar, 2025

Pandas a powerful Python library for data manipulation provides the to_json() function to convert a DataFrame into a JSON file and the read_json() function to read a JSON file into a DataFrame.

In this article we will explore how to export a Pandas DataFrame to a JSON file with detailed explanations and beginner-friendly steps.

Exporting Pandas DataFrame to JSON

To export a Pandas DataFrame to a JSON file we use the to_json() function. This function converts the DataFrame into a JSON format making it easy to store and share data. To read the JSON file back into a DataFrame we use the read_json() function. Let’s explore some examples to understand how they work.

Example 1: Exporting a Simple DataFrame

This example demonstrates how to create a small DataFrame with three rows and three columns and save it as a JSON file.

Python `

import pandas as pd

df = pd.DataFrame([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']], index=['row 1', 'row 2', 'row 3'], columns=['col 1', 'col 2', 'col 3'])

df.to_json('file.json', orient='split', compression='infer', index=True)

df = pd.read_json('file.json', orient='split', compression='infer') print(df)

`

**Output :

We can see that the DataFrame has been exported as a JSON file.

Example 2: Exporting a More Detailed DataFrame

In this example we create a DataFrame containing employee details such as **ID, Name and Date of Joining. The JSON file is exported using the split orientation which efficiently organizes the data by storing **indexes, column names and values separately.

Python `

import pandas as pd

df = pd.DataFrame(data=[ ['15135', 'Alex', '25/4/2014'], ['23515', 'Bob', '26/8/2018'], ['31313', 'Martha', '18/1/2019'], ['55665', 'Alen', '5/5/2020'], ['63513', 'Maria', '9/12/2020']], columns=['ID', 'NAME', 'DATE OF JOINING'])

df.to_json('file1.json', orient='split', compression='infer')

df = pd.read_json('file1.json', orient='split', compression='infer') print(df)

`

**Output :

We can see that this DataFrame has also been exported as a JSON file.

JSON Orientations in Pandas

Pandas supports multiple **orient options for JSON format allowing different ways to structure the data. Choosing the right orientation depends on the use case.

**Example:

Python `

df.to_json('file.json', orient='records')

`

This saves the DataFrame as a list of dictionaries.