Hello, folks! In this article, we will be focusing on Exporting a JSON file to a CSV file using Python.

So, let us begin!


Table of Contents

  • 1 Steps to export a JSON file into a CSV file
    • 1.1 1. Import the necessary libraries
    • 1.2 2. Store the heading/column values of the json data into a list
    • 1.3 3. Pass the path of the CSV file
  • 2 Conclusion

Steps to export a JSON file into a CSV file

JSON is an acronym for JavaScript Object Notation. It is an executable script that enables us to store and transfer data from one platform to another at an ease. We often come across situations wherein we need data to be scrapped from certain sources. So, what is the output form of the scraped data??

It is JSON!! This format enables us to have the data in the form of key-value pairs. The entire data is stored as a ‘string’ in a key value format.

But, what if I want this data in JSON to be pushed further to database for manipulations? The easiest possible solution that comes to my mind is Exporting the JSON file as CSV file.

So, let us now have a look at the steps we need to follow to convert/export a JSON file into a CSV (Comma Separated Values) format.


1. Import the necessary libraries

In order to work with CSV files, we need to import the built-in module available as shown-

import csv

2. Store the heading/column values of the json data into a list

While working with exporting the JSON data into CSV format, it is very essential for us to specify the header values or column names of each column.

Thus, we create a separate list and pass the key tags to the created list as shown below –

cols = ['Name', 'Age', 'Gender']

An important thing to note is that if the column names stored in the above-created variable doesn’t match one of the key tags in the JSON file, it will definitely throw an error.

3. Pass the path of the CSV file

Now, it is time for us to open the CSV file and point an object to it. Further, we use the csv.DictWriter() function to write/export the JSON data into CSV form.

We create an instance of the DictWriter() function and then place the column values into the CSV file. In the end, we would export the data values using writerows() function as shown below–

with open(path, 'w') as f: 
    wr = csv.DictWriter(f, fieldnames = cols) 
    wr.writeheader() 
    wr.writerows(data) 

You can find the entire code below! 🙂

import csv 

cols = ['Name', 'Age', 'Gender'] 

data = [ 
{'Name': 'John', 'Age': '20', 'Gender': 'Male'}, 
{'Name': 'James', 'Age': '28', 'Gender': 'Male'},    
{'Name': 'Cardi', 'Age': '25', 'Gender': 'Female'} 
] 
path = "C:/Users/HP/OneDrive/Desktop/DEMO.csv"
with open(path, 'w') as f: 
    wr = csv.DictWriter(f, fieldnames = cols) 
    wr.writeheader() 
    wr.writerows(data) 

#python #json #javascript #developer

JSON to CSV: Export a JSON file to a CSV file using Python
7.45 GEEK