How to Export a pandas DataFrame as a JSON File
In this tutorial, you will learn how to .
TLDR solution
df.to_json("target-path/csv-file-name.json")
Step-by-Step Example
Suppose, you have the following DataFrame:
import pandas as pd
data = {'fish': ['salmon', 'pufferfish', 'shark'],
'count': [100, 10, 1],
}
df = pd.DataFrame(data)
print(df)
fish count
0 salmon 100
1 pufferfish 10
2 shark 1
Export this DataFrame as JSON file on your desktop using the to_json method:
import os
desktop_path = os.path.expanduser('~/Desktop')
df.to_json(desktop_path + '/fish.json', orient='columns')
After you run this, you should find a fish.json file on your desktop.
Open it with a text editor and you should see the following content:
orient='columns' (default)
{
"fish":{"0":"salmon","1":"pufferfish","2":"shark"},
"count":{"0":100,"1":10,"2":1}
}
Other Orient Options
Adjust the orient option according to your requirements:
orient='records'
[
{"fish":"salmon","count":100},
{"fish":"pufferfish","count":10},{"fish":"shark","count":1}
]
orient='split'
{
"columns":["fish","count"],
"index":[0,1,2],
"data":[["salmon",100],["pufferfish",10],["shark",1]]
}
orient='index'
{
"0":{"fish":"salmon","count":100},
"1":{"fish":"pufferfish","count":10},"2":{"fish":"shark","count":1}
}
orient='values'
[["salmon",100],["pufferfish",10],["shark",1]]
orient='table'
{
"schema":{
"fields":[
{"name":"index","type":"integer"},
{"name":"fish","type":"string"},
{"name":"count","type":"integer"}
],
"primaryKey":["index"],"pandas_version":"1.4.0"},
"data":[
{"index":0,"fish":"salmon","count":100},
{"index":1,"fish":"pufferfish","count":10},
{"index":2,"fish":"shark","count":1}
]
}
That's it! You just learned to export a DataFrame as a JSON file.