Sometimes, we want to convert JSON to CSV with Python.
In this article, we’ll look at how to convert JSON to CSV with Python.
How to convert JSON to CSV with Python?
To convert JSON to CSV with Python, we can use Pandas.
For instance, if our JSON file has:
test.json
[
{
"pk":22,
"model":"auth.permission",
"fields":{
"codename":"add_logentry",
"name":"Can add log entry",
"content_type":8
}
},
{
"pk":23,
"model":"auth.permission",
"fields":{
"codename":"change_logentry",
"name":"Can change log entry",
"content_type":8
}
},
{
"pk":24,
"model":"auth.permission",
"fields":{
"codename":"delete_logentry",
"name":"Can delete log entry",
"content_type":8
}
},
{
"pk":4,
"model":"auth.permission",
"fields":{
"codename":"add_group",
"name":"Can add group",
"content_type":2
}
},
{
"pk":10,
"model":"auth.permission",
"fields":{
"codename":"add_message",
"name":"Can add message",
"content_type":4
}
}
]
Then we write:
import pandas as pd
from pathlib import Path
import json
p = Path('test.json')
with p.open('r', encoding='utf-8') as f:
data = json.loads(f.read())
df = pd.json_normalize(data)
df.to_csv('test.csv', index=False, encoding='utf-8')
We create a Path
instance with the path of the JSON file.
Then we call p.open
with 'r'
to read the JSON file.
Next, we call json.loads
to load the JOSN file into JSON.
Next, we call pd.json_normalize
with the JSON data for the file to flatten it.
Then we call df.to_csv
with the file path of the file to save to and the encoding to save the CSV file.
Therefore, test.csv
has:
pk,model,fields.codename,fields.name,fields.content_type
22,auth.permission,add_logentry,Can add log entry,8
23,auth.permission,change_logentry,Can change log entry,8
24,auth.permission,delete_logentry,Can delete log entry,8
4,auth.permission,add_group,Can add group,2
10,auth.permission,add_message,Can add message,4
Conclusion
To convert JSON to CSV with Python, we can use Pandas.