Introduction to JSON to CSV in Python
In this article, we will see the conversion of JSON to CSV using Python. JSON files typically consist of a JavaScript Object Notation, which is used to transmit and receive data utilizing the Python json module. To utilize its features, the module must first be imported into the Python program. A CSV file stores data in a tabular, spreadsheet, or database format, using comma-separated values to separate and represent the data. To use these features in the Python program, we need to import csv module. In this article, we convert JSON to CSV by using Python scripts to transform JSON data into key-value pairs. We assign these keys as headers for the CSV file and populate the CSV file with descriptive data.
How to Convert JSON to CSV in Python?
In this article, to convert JSON to CSV using Python scripts, we first need to import json and csv modules, which are built-in modules in Python. In Python, we have to use a few methods of json modules, such as “load” for extracting data from the JSON file, which will be saved as dictionary keys. And also csv module methods such as DictWriter() to write data to CSV files. To convert any JSON file to a CSV file using Python programming language, we have to make JSON keys as headers to convert it into a CSV file.
Firstly we will see how to parse JSON data in Python, which is an important part of converting JSON data to CSV format. Let us see the Python sample code for parsing JSON data using the json module along with the load() method. First, let us see below the JSON data sample and save it as a JSON file with the file name JSONdata.json
{
"course_details": [
{
"c_name": "Android",
"fees": "25000",
"c_place": "Chennai"
}
]
}
No, we will write a Python script to parse the above JSON data.
Examples of JSON to CSV Python
Below are the different examples mentioned:
Example #1
Code:
import json
print("Program to demonstrate JSON parsing using Python")
print("\n")
course ='{"c_name":"Android", "fees": "25000", "c_place":"Chennai"}'
course_dict = json.loads(course)
print("JSON data is as follows:")
print(course_dict)
print("\n")
print("Printing particular field in JSON data using data as keys in course dictionary")
print(course_dict['c_name'])
Output:
In the above program, we can see we have declared a “course” variable for writing JSON data, and then we have created a dictionary so that we can parse the JSON data using the “loads” method provided by the Python built-in module “json” for dealing with JSON format files. So in the above screenshot, we saw how to print entire JSON data and also how to print particular data using keys. This is very important for writing headers in the CSV file so that we can convert JSON data to CSV files. In the below section, we will see how to do this process. Let us demonstrate it in the below example:
Example #2
Code:
import json
import csv
print("Program to demostrate conversion of json to csv")
print("\n")
with open('JSONdata.json') as json_file:info = json.load(json_file)
print("JSON file JSONdata.json is opened for reading")
print("\n")
emp_info = info['emp_details']
csv_file = open('converter_csv_file.csv', 'w')
print("CSV file is opened for writing JSON data")
print("\n")
csv_writer = csv.writer(csv_file)
count = 0
print("Writing headers to file")
print("\n")
for e in emp_info:
if count == 0:
header_csv = e.keys()
csv_writer.writerow(header_csv)
count += 1
csv_writer.writerow(e.values())
print("JSON file is converted to CSV file")
csv_file.close()
Output:
In the above program, first, we need to import json and csv modules, and later we can see “JSONdata.json” which is a JSON file that contains the below data.
The above screenshot is the JSON file that contains data in JSON format. We first open the file for reading and then extract the JSON data by utilizing the “load” method of the json module. The parsing of the JSON format is primarily done through this method. After this, we open the CSV file in writing mode “w” and convert the data to CSV format.. Then we will write the headers read each key through for loop, and then write each data value in the CSV file using the csv module’s writerow() method. We can then find the output in the current directory where the JSON file is located. You can open the resulting CSV file in Excel or view it in Notepad to see the correctly formatted comma-separated values. We can see it in the screenshot CSV file.
The CSV file shown above is the result of converting a file from JSON format to CSV format.
We can also convert back these CSV files back to JSON files where the process is just opposite to the above process. Firstly we will read CSV data values and then write these data values in JSON format. In Python, we use DictReader() function to read CSV files and use the dump() and write() methods of json module. But we have to remember when opening the file; we should properly mention the modes of files, such as for reading “r” and writing “w”. We should also close the file at the end of the program to convert JSON format to CSV or vice versa, and then after writing the data to the file, whether we are writing it to a CSV file or a JSON file.
Conclusion
In this article, we conclude that the conversion of JSON format to CSV format in the Python programming language is simple. Using the methods of the json and csv modules, you can easily convert a JSON file to a CSV file. In this article, we saw first how to parse the JSON data in Python using the “loads()” method, and then we saw how to write the converted JSON data to a CSV file using the writer() method of the csv module in Python. We also saw an example of converting the JSON data file to a CSV file with screenshots of the output of the program.
Recommended Articles
We hope that this EDUCBA information on “JSON to CSV Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.