Convert JSON to CSV in Python

The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script. The text in JSON is done through quoted string which contains the value in key-value mapping within { }. It is similar to the dictionary in Python.

CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.

Refer to the below articles to understand the basics of JSON and CSV.

Converting JSON to CSV

For a simple JSON data consisting of key and value pairs, keys will be headers for CSV file and values the descriptive data.

Example: Suppose the JSON file looks like this:


We want to convert the above JSON to CSV file with key as headers.





# Python program to convert
# JSON file to CSV
import json
import csv
# Opening JSON file and loading the data
# into the variable data
with open('data.json') as json_file:
    data = json.load(json_file)
employee_data = data['emp_details']
# now we will open a file for writing
data_file = open('data_file.csv', 'w')
# create the csv writer object
csv_writer = csv.writer(data_file)
# Counter variable used for writing 
# headers to the CSV file
count = 0
for emp in employee_data:
    if count == 0:
        # Writing headers of CSV file
        header = emp.keys()
        count += 1
    # Writing data of CSV file




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.