Convert JSON to CSV using Python
In this post, you will learn different ways to convert JSON to a CSV file.
JSON (JavaScript Object Notation) is popular among developers for data serialization. It is a data format consisting of key value pairs. It is used widely to transmit and receive data between a server and a web application in JSON format. It is so popular that, every modern programming language has methods to generate and parse JSON formatted data.
In the wake of dealing with a dataset and doing all the pre-processing, we require to save the pre-processed information into some data format like in csv, excel or others. CSV (Comma-separated-values) is widely used for data exchange in data based applications. In web applications, we generally store the data in arrays, dataframes, lists, tuples, dictionaries, etc. There may be need for clients to export these data to a CSV file. The data in CSV is stored as sequences of records. Like in other programming languages, we can also write data to a CSV file.
Converting JSON to CSV using JSON module
Suppose we have the following JSON data that contains 'student' data-
{
"student_details":[
{
"Roll": 1001,
"class": 10,
"firstname": "Priska",
"lastname": "Kashyap",
"section": "A"
},
{
"Roll": 1002,
"class": 10,
"firstname": "John",
"lastname": "Smith",
"section": "B"
},
{
"Roll": 1003,
"class": 10,
"firstname": "Aditya",
"lastname": "Roi",
"section": "A"
}
]
}
In the given code, we will convert JSON files to CSV using Python's inbuilt modules called json and csv. The following code converts the above JSON to CSV file with the keys as headers. First we import both modules. Then read the JSON file and extract the data. Next, we open the CSV file and write the JSON data to the CSV file. The JSON data consists of key and value pairs, where keys will be headers for the CSV file and values will be the descriptive data.
# Python program to convert
# JSON file to CSV
import json
import csv
# Opening and loading the JSON data
with open('student.json') as json_file:
data = json.load(json_file)
stu_data = data['student_details']
# Open csv file for writing
data_file = open('student_file.csv', 'w')
# create the csv writer object
csv_writer = csv.writer(data_file)
# defining counter variable for writing
# headers to the CSV file
count = 0
for stu in stu_data:
if count == 0:
# Writing headers of CSV file
header = stu.keys()
csv_writer.writerow(header)
count += 1
# writing data of CSV file
csv_writer.writerow(stu.values())
data_file.close()
We get the following CSV file:
Converting JSON to CSV using pandas
Python Pandas is an open source, fast, easy-to-use tool for data manipulation and data analysis. It provides rich data structures and functions to make data analysis easy and fast. Here, you will learn how to convert JSON to CSV using Python pandas. If you haven't installed the Pandas module, you can easily install the Pandas module with the PIP tool.
pip install pandas
The following code demonstrates how to convert JSON to CSV using Python pandas.
import pandas as pd
df = pd.read_json (r'C:\Users\Ron\Desktop\Test\Product_List.json')
df.to_csv (r'C:\Users\Ron\Desktop\Test\New_Products.csv', index = None)
Related Articles
Convert MySQL query result to JSON in Python
Insert JSON data into MongoDB using Python
Python read JSON from URL requests
Python convert XML to JSON
Convert list to dictionary Python
Python dict inside list
Pandas string to datetime
Convert Excel to CSV Python Pandas
Python add list to list
Python Pandas Dataframe to CSV
Python compare two lists
Remove element from list Python
Python iterate list with index
Python program to sum all the numbers in a list
Python print without newline
Python iterate list with index
Python convert xml to dict
Python dict inside list
Python convert dict to xml
Python weather api
Python raise keyword