Reputation: 67
I try to convert CSV file(; delimited) to JSON file and my CSV file structure is like below sample: ID;NAME;AGE;CLASS;SEC 1;ram;13;8;B
like that
import csv,json
csvf_path='xyz'
jsonf_path='mnb'
Data={}
with csv(csvf_path) as csvFile:
csvRider=csv.DictReader(csvFile)
for csvRow as csvRider:
ID=csvRow('ID')
data[Id]=csvRow
with open(jsonf_path,'W') as jsonFile
jsonFile.write(json.dumps(data,indent=4))
-->data[Id]=csvRow ---->error---->KEyerror i also try it using
csv.reader(csvf_path,delimiter=';')
then again I got an error,
TypeError: list indices must be integers or slices, not str. -->
ID=ID=csvRow('ID')
Upvotes: 1
Views: 57
Reputation: 44093
The indentation in the provided code is wrong. Take a look at this part:
csvRider=csv.DictReader(csvFile)
for csvRow as csvRider:
ID=csvRow('ID')
data[Id]=csvRow
The for
should be indented.
;
) into JSON
import csv
import json
with open('data.csv') as f:
reader = csv.DictReader(f, delimiter=';')
rows = list(reader)
with open('result.json', 'w') as f:
json.dump(rows, f)
Result:
[
{
"ID": "1",
"NAME": "ram",
"AGE": "13",
"CLASS": "8",
"SEC": "1"
}
]
Upvotes: 1