How to Convert CSV to JSON in Python
Python has a built-in module called csv that provides functions to read and write tabular data in CSV format. Python also has json built-in module which helps to serialize and deserialize JSON data. In this example, we will use both of these built-in Python modules to convert CSV format data to JSON format data.
Let the CSV file data be the following:
name,course,id Jonny,Programming,1 Joe,Engineering,2 Danny,Scientist,3 Leni,Doctor,4
The code below converts data of a CSV file to JSON in Python:
import csv
import json
file_path = "D:\data.csv"
with open(file_path, mode='r') as csvfile:
csvreader = csv.reader(csvfile)
# read first row field names
fields = next(csvreader)
rows = []
for row in csvreader:
data_as_dict = {}
i = 0
for value in row:
data_as_dict[fields[i]] = value
i += 1
rows.append(data_as_dict)
json_data = json.dumps(rows, indent=4)
print(json_data)
print("Total number of row in csv file: %d" % (csvreader.line_num))
# removing data from rows
rows.clear()
print("Complete...")
The output of the above code is as follows:
[ { "name": "Jonny", "course": "Programming", "id": "1" }, { "name": "Joe", "course": "Engineering", "id": "2" }, { "name": "Danny", "course": "Scientist", "id": "3" }, { "name": "Leni", "course": "Doctor", "id": "4" } ] Total number of row in csv file: 5 Complete...