Skip to content
Related Articles

Related Articles

Improve Article

Exporting Pandas DataFrame to JSON File

  • Last Updated : 18 Aug, 2020

Let us see how to export a Pandas DataFrame as a JSON file. To perform this task we will be using the DataFrame.to_json() and the pandas.read_json() function.

Example 1 :




# importing the module
import pandas as pd
  
# creating a DataFrame
df = pd.DataFrame([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']],
                  index =['row 1', 'row 2', 'row3'],
                  columns =['col 1', 'col 2', 'col3'])
  
# storing the data in JSON format
df.to_json('file.json', orient = 'split', compression = 'infer', index = 'true')
  
# readind the JSON file
df = pd.read_json('file.json', orient ='split', compression = 'infer')
  
# displaying the DataFrame
print(df)

Output : 


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

Example 2 :






# importing the module
import pandas as pd
   
# creating a DataFrame
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'])
  
# storing data in JSON format
df.to_json('file1.json', orient = 'split', compression = 'infer')
  
# reading the JSON file
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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :