How To Convert JSON To CSV in Python

In this tutorial, We will learn how to convert JSON (JavaScript Object Notation) to CSV (Comma Separated Values) file using Python.

JSON is a popular data format used for data manipulation. CSV is a popular format for spreadsheets and databases. Sometimes we come across situations when we need to convert the JSON file to CSV file. So let’s start…

Convert JSON to CSV using Python

Let’s consider the following JSON file (save it as ‘json_string.json’) that should be converted into a CSV file.

{"website":"codespeedy","topic":"json and python","year":2019,"list":[10,20,30]}

The first thing we need to do is to import the ‘json’  and the ‘csv’ library as shown below.

import json
import csv

Now open the JSON file in reading mode and open the CSV file in write mode as shown below.

json_file=open('json_string.json','r')
csv_file=open('csv_format.csv','w')

You have to convert the JSON data into a Python dictionary using the ‘load’ method. Call the ‘writer’ function passing the CSV file as a parameter and use the ‘writerow’ method to write the JSON file content (now converted into Python dictionary) into the CSV file. You can use ‘.keys()’ and ‘.values()’ to write the dictionary keys and dictionary values in different rows into the CSV file respectively. See the complete code.

import json
import csv

json_file=open('json_string.json','r')
csv_file=open('csv_format.csv','w')

json_data_to_python_dict=json.load(json_file)
write=csv.writer(csv_file)

write.writerow(json_data_to_python_dict.keys())
write.writerow(json_data_to_python_dict.values())
json_file.close()
csv_file.close()

Output:

How To Convert JSON To CSV in Python

This is the CSV file ‘csv_format.csv’ created from the JSON file ‘json_string.json’.

Note that you should close the CSV file to save the contents of the CSV file (csv_file.close()).

You may also read-

Leave a Reply

Your email address will not be published. Required fields are marked *