How to Convert JSON to CSV in Python

By Ken Burnside

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 1

Copy and paste the following code into a text file:import jsonimport csv f = open('test.json')data = json.load(f)f.close()f=csv.writer(open('test.csv','wb+'))for item in data:f.writerow([item['pk'], item['model']] + item['fields'].values())

Step 2

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

Step 3

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

Step 4

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