Convert CSV To JSON in Python
In this example, we will read and convert a CSV file data to JSON in Python.
Let our CSV file be the following:
myfile.csv
name,course,id
Jonny,Programming,A
Joe,Engineering,B
Danny,Scientist,C
Leni,Doctor,D
Example of Python code to read and convert CSV data to JSON:
import csv
import json
def default(o):
if hasattr(o, 'to_json'):
return o.to_json()
raise TypeError(
f'Object of type {o.__class__.__name__} is not JSON serializable')
file = "myfile.csv"
with open(file, 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)
msg = str(json.dumps(rows, default=default))
print(msg)
print("Total number of row in csv file: %d" % (csvreader.line_num))
rows.clear()
print("Complete...")
Output
{`[{"name": "Jonny", "course": "Programming", "id": "A"},
{"name": "Joe", "course": "Engineering", "id": "B"},
{"name": "Danny", "course": "Scientist", "id": "C"},
{"name": "Leni", "course": "Doctor", "id": "D"}]`}
Total number of row in csv file: 5
Complete...
Total number of row in csv file: 5
Complete...