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
CodePudding user response:
You aren't reading the CSV file the correct way. Use csv.DictReader
to read each row as a dictionary. Then, you'll be able to use for m in reader: key = m['Order ID']
.
Change reader = csvfile.read()
to reader = csv.DictReader(csvfile)
As of now, reader
is a string that contains all the contents of your file. for m in reader
makes m
each character in this string, and you cannot access the "Order ID"
key on a character.
After you make the change, reader
will be a DictReader
object, and iterating over it will return each row as a dictionary.
CodePudding user response:
You can use csv.DictReader
.
reader = csv.DictReader(csvfile)
for line in reader:
key = line['Order ID']
contents[key] = m