I am trying to convert a csv file to a json file by reading the content of the csv file and writing it to a new json file. I am encountering an error that is at the point where I try to make a column of the csv file into dictionary keys. How can I resolve this error?
My code for reference:
import csv
import json
def jsonformat(infile,outfile):
contents = {}
csvfile = open(infile, 'r')
reader = csvfile.read()
for m in reader:
key = m['Order ID']
contents[key] = m
jsonfile = open(outfile, 'w')
json_contents = json.dumps(contents, indent = 4)
jsonfile.write(json_contents)
csvfile.close()
jsonfile.close()
return json_contents
infile = 'orders.csv'
outfile = 'orders.json'
output = jsonformat(infile,outfile)
print(output)
error message: TypeError Traceback (most recent call last) in 28 outfile = 'orders.json' 29 ---> 30 output = jsonformat(infile,outfile) 31 32 print(output)
in jsonformat(infile, outfile) 12 13 for m in reader: ---> 14 key = m['Order ID'] 15 contents[key] = m 16
TypeError: string indices must be integers
