To export a Pandas DataFrame to a JSON file we use 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.
Example: This example demonstrates how to create a small DataFrame with three rows and three columns and save it as a JSON file.
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.
Explanation:
- pd.DataFrame(...) creates a DataFrame with given data, index, and column names
- df.to_json(...) converts the DataFrame into JSON format and saves it as a file
- orient='split' stores data as index, columns, and values separately
- compression='infer' automatically decides compression (no compression here)
- index=True includes row labels (index) in the JSON file
- pd.read_json(...) reads the JSON file back into a DataFrame
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.
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.
Explanation:
- pd.DataFrame(data=[...]) creates a DataFrame using employee records
- columns=[...] assigns column names like ID, NAME, and DATE OF JOINING
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.
- records: list of dictionaries
- columns: dictionary with column labels
- index: dictionary with row indices
- split: dictionary with index, columns and data
- table: JSON table schema
df.to_json('file.json', orient='records')
Explanation:
- df.to_json('file.json', orient='records') converts the DataFrame into a list of dictionaries format
- Each row becomes a separate JSON object and this format is useful for APIs and data exchange