Converting CSV to JSON array in Python
Hello folks, today we are going to learn how to convert CSV data to JSON array in Python.
Convert CSV to JSON array using CSV and JSON libraries in Python
Let us consider in a folder there are two files. One is csvfile.csv and the other one is jsonfile.json
jsonfile,json is an empty file.
csvfile.csv consists of the following data:
Student id, Course id, Marks
1001, 2001, 56
1002, 2001, 67
1003, 2001, 78
1004, 2001, 90
1005, 2001, 45
1001, 2002, 58
1002, 2002, 98
1009, 2002, 12
1007, 2002, 99
1008, 2002, 39
1003, 2003, 34
1004, 2003, 43
1000, 2003, 25
1060, 2003, 60
1090, 2003, 88
1005, 2004, 81
1080, 2004, 59
1030, 2004, 87
1001, 2004, 35
1090, 2004, 33
Our goal is to convert the above CSV data into JSON array and store it in jsonfile.json
Libraries used:
- csv
- json
Steps:
- Declare a dictionary called jsondict
- Open and read the CSV file
- Declare a list in jsondict for a key
- Now append each row in that list
- After appending all the rows, open jsonfile.json and dump the dictionary using json.dumps() method.
Code:
import csv import json def csv_to_json(csvFile, jsonFile): jsondict = {} with open(csvFile) as csvfile: csv_data = csv.DictReader(csvfile)#Converting the csv data into dictionary jsondict["data"]=[] for rows in csv_data: print(rows)#Just for reference jsondict["data"].append(rows) #Appending all the csv rows with open(jsonFile, 'w') as jsonfile: #Dumping the data into jsonfile.json jsonfile.write(json.dumps(jsondict, indent = 4)) #indent is used for pretty printing csvfile = 'csvfile.csv' jsonfile = 'jsonfile.json' csv_to_json(csvfile, jsonfile)#Calling the function
Output:
After executing the above code,csv data is converted into json data and stored in jsonfile.json
Also Read:
Leave a Reply