I have the below code to iterate through my CSV values. Input data (Sample.csv):
name,city
jack,nj
matt,ny
and create output in JSON. Required output
[
{"name": "jack","city": "PA"},
{"name": "matt","city": "CA"}
]
Output from code:
[{"name,city": "jack,PA"};{"name,city": "matt,CA"};]
Code sample:
#!/usr/bin/python
import json
import csv
csvfile = open('sample.csv', 'r')
jsonfile = open('sample.csv'.replace('.csv','.json'), 'w')
jsonfile.write('{\n[\n')
fieldnames = csvfile.readline().replace('\n','').split(';')
reader = csv.DictReader(csvfile, fieldnames, delimiter=';')
from collections import OrderedDict
for row in reader:
json.dump(OrderedDict([(f, row[f]) for f in fieldnames]), jsonfile, indent=4)
jsonfile.write(';\n')
jsonfile.write(']\n}')
Final output is not aligning into key value pair.
fieldnamesdirectly if the first line of the CSV file is the field names. Also it's not clear why you are manually mangling the JSON in the output file. Also, given that the delimiter is clearly,, why do you keep using;?!