How to Create a JSON File from a Pandas DataFrame in Python
In Pandas, you can use the to_json() method to convert a DataFrame to a JSON file. This method takes several arguments, such as the file path, the orient, and indent. I have an another article How to Create a Pandas DataFrame in Python, where you will learn how to create a Pandas DataFrame in Python. In this tutorial, I will use a sample DataFrame as below:
id name math_score 0 202301 Minhaj 92 1 202302 Ridhwan 86 2 202303 Tanveer 76 3 202304 Sharodia 89 4 202305 Alve 99 5 202306 Intisar 99
Here’s an example of how you might use this to_json()method to write a DataFrame to an JSON file:
import pandas as pd
# Write the DataFrame to a JSON file
df.to_json(r'C:\Users\Minhaj\Desktop\data.json', orient='records', indent=4)
This will create a file named data.json in the current working directory, with the contents of the DataFrame in JSON format. Contents of the above written JSON file:
[
{
"id":"202301",
"name":"Minhaj",
"math_score":92
},
{
"id":"202302",
"name":"Ridhwan",
"math_score":86
},
{
"id":"202303",
"name":"Tanveer",
"math_score":76
},
{
"id":"202304",
"name":"Sharodia",
"math_score":89
},
{
"id":"202305",
"name":"Alve",
"math_score":99
},
{
"id":"202306",
"name":"Intisar",
"math_score":99
}
]
The orient parameter of the to_json() method allows you to specify the format of the JSON file. The default value is ‘columns’, which means the JSON file will have the column names as the top-level keys.
You can also use the json module to convert a DataFrame to a JSON string and then write it to a file:
import json
# Convert DataFrame to a JSON string
data_json = df.to_json(orient='records')
# Write JSON string to a file
with open(“data.json”, “w”) as f:
f.write(json.dumps(data_json))
In this tutorial, I tried to brief how to create an JSON file from a Pandas DataFrame in Python. Hope you have enjoyed the tutorial. If you want to get updated, like my facebook page https://www.facebook.com/LearningBigDataAnalytics and stay connected.