How to Convert JSON to CSV in Python

JSON is a file format used by Python and several other programming languages to store structured, hierarchical data. CSV is short for “Comma Separated Values,” which is a file format that separates values using commas as delimiters. JSON files can have much more complex structures than CSV files, so a direct conversion is not always possible. Python has several techniques and libraries that can be loaded to help with this conversion.

Step

Copy and paste the following code into a text file:

Step

import json import csv

Step

f = open('test.json') data = json.load(f) f.close()

Step

f=csv.writer(open('test.csv','wb+'))

Step

for item in data: f.writerow([item['pk'], item['model']] + item['fields'].values())

Step

Replace the parts of the code that refer to “test.json” and “test.csv” with the file names you wish to use.

Step

Save the file as “json2csv.py” in your Python working directory.

Step

Start your Python interpreter and load “json2csv.py” to run it.