Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I have a JSON file that I want to convert 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 

]

1 Answer

0 votes
by (106k points)

To convert JSON to CSV you can use the pandas library:-

pandas.read_json()

If you want to convert a JSON string to a pandas object either a series or dataframe. Then, assuming the results were stored as df:

df.to_csv()

Related questions

0 votes
1 answer
asked Jan 18, 2020 in Python by Rajesh Malhotra (19.9k points)
0 votes
1 answer
0 votes
1 answer
asked Dec 10, 2020 in Python by laddulakshana (16.4k points)
0 votes
1 answer

Browse Categories

...