Open In App

Convert JSON to CSV in Python

Last Updated : 29 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 simple JSON data consisting of key and value pairs, keys will be headers for the CSV file and values the descriptive data.
 

Example: Suppose the JSON file looks like this:
 

python-json-to-csv

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

Python3




# 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()
        csv_writer.writerow(header)
        count += 1
 
    # Writing data of CSV file
    csv_writer.writerow(emp.values())
 
data_file.close()


Output:
 

python-json-to-csv-output

And, if you are working on JSON data like the following:

[

    {‘Age’: 18.0, ‘Salary’: 20000.0, ‘Gender’: ‘Male’, ‘Country’: ‘Germany’, ‘Purchased’: ‘N’}

    {‘Age’: 19.0, ‘Salary’: 22000.0, ‘Gender’: ‘Female’, ‘Country’: ‘France’, ‘Purchased’: ‘N’}

    {‘Age’: 20.0, ‘Salary’: 24000.0, ‘Gender’: ‘Female’, ‘Country’: ‘England’, ‘Purchased’: ‘N’}

]

The below code will work perfectly for you (please format the code before running)

Python3




import json
import csv
 
with open('G:\Akhil\jsonoutput.json') as json_file:
    jsondata = json.load(json_file)
 
data_file = open('G:\Akhil\jsonoutput.csv', 'w', newline='')
csv_writer = csv.writer(data_file)
 
count = 0
for data in jsondata:
    if count == 0:
        header = data.keys()
        csv_writer.writerow(header)
        count += 1
    csv_writer.writerow(data.values())
 
data_file.close()


 



Previous Article
Next Article

Similar Reads

Convert CSV to JSON using Python
CSV (or Comma Separated Value) files represent data in a tabular format, with several rows and columns. An example of a CSV file can be an Excel Spreadsheet. These files have the extension of .csv, for instance, geeksforgeeks.csv. In this sample file, every row will represent a record of the dataset, and each column will indicate a unique feature v
2 min read
Convert multiple JSON files to CSV Python
In this article, we will learn how to convert multiple JSON files to CSV file in Python. Before that just recall some terms : JSON File: A JSON file may be a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which may be a standard data interchange format. It is primarily used for transmitting data bet
8 min read
Convert nested JSON to CSV in Python
In this article, we will discuss how can we convert nested JSON to CSV in Python. An example of a simple JSON file: As you can see in the example, a single key-value pair is separated by a colon (:) whereas each key-value pairs are separated by a comma (,). Here, "name", "profile", "age", and "location" are the key fields while the corresponding va
9 min read
Python program to read CSV without CSV module
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 nam
3 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Saving Text, JSON, and CSV to a File in Python
Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats. Opening a text file in Python Opening a file refers to getting the file ready either for reading or for writing. This can be don
5 min read
Saving scraped items to JSON and CSV file using Scrapy
In this article, we will see how to use crawling with Scrapy, and, Exporting data to JSON and CSV format. We will scrape data from a webpage, using a Scrapy spider, and export the same to two different file formats. Here we will extract from the link http://quotes.toscrape.com/tag/friendship/. This website is provided by the makers of Scrapy, for l
5 min read
Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
Convert CSV to Excel using Pandas in Python
Pandas can read, filter, and re-arrange small and large datasets and output them in a range of formats including Excel. In this article, we will be dealing with the conversion of .csv file into excel (.xlsx). Pandas provide the ExcelWriter class for writing data frame objects to excel sheets. Syntax: final = pd.ExcelWriter('GFG.xlsx') Example:Sampl
1 min read