I have a JSON file that I want to covert to a CSV file. How can I do this with Python?
I tried:
import json
import csv
f = open('data.json')
data = json.load(f)
f.close()
f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
f.writerow(item)
f.close()
However, it did not work. I am using Django and the error I received is:
file' object has no attribute 'writerow'
So, then I tried the following:
import json
import csv
f = open('data.json')
data = json.load(f)
f.close()
f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
csv_file.writerow(item)
f.close()
I then get the error:
sequence expected
Sample json file:
[
{
"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
}
}
]
I am not sure this question is solved already or not, but let me paste what I have done for reference.
First, your JSON has nested objects, so it normally cannot be directly converted to CSV. You need to change that to something like this:
Here is my code to generate CSV from that:
You will get output as:
A generic solution which translates any json list of flat objects to csv.
Pass the input.json file as first argument on command line.
With the
pandas
library, this is as easy as using two commands!To convert a JSON string to a pandas object (either a series or dataframe). Then, assuming the results were stored as
df
:Which can either return a string or write directly to a csv-file.
Based on the verbosity of previous answers, we should all thank pandas for the shortcut.
It'll be easy to use
csv.DictWriter()
,the detailed implementation can be like this:Note that this assumes that all of your JSON objects have the same fields.
Here is the reference which may help you.
This code should work for you, assuming that your JSON data is in a file called
data.json
.I was having trouble with Dan's proposed solution, but this worked for me:
Where "test.json" contained the following: