I want to convert CSV to JSON in python. I was able to convert simple csv files to json, but not able to join two csv into one nested json.
emp.csv:
empid | empname | empemail
e123 | adam | [email protected]
e124 | steve | [email protected]
e125 | brian | [email protected]
e126 | mark | [email protected]
items.csv:
empid | itemid | itemname | itemqty
e123 | itm128 | glass | 25
e124 | itm130 | bowl | 15
e123 | itm116 | book | 50
e126 | itm118 | plate | 10
e126 | itm128 | glass | 15
e125 | itm132 | pen | 10
the output should be like:
[{
"empid": "e123",
"empname": "adam",
"empemail": "[email protected]",
"items": [{
"itemid": "itm128",
"itmname": "glass",
"itemqty": 25
}, {
"itemid": "itm116",
"itmname": "book",
"itemqty": 50
}]
},
and similar for others]
the code that i have written:
import csv
import json
empcsvfile = open('emp.csv', 'r')
jsonfile = open('datamodel.json', 'w')
itemcsvfile = open('items.csv', 'r')
empfieldnames = ("empid","name","phone","email")
itemfieldnames = ("empid","itemid","itemname","itemdesc","itemqty")
empreader = csv.DictReader( empcsvfile, empfieldnames)
itemreader = csv.DictReader( itemcsvfile, itemfieldnames)
output=[];
empcount=0
for emprow in empreader:
output.append(emprow)
for itemrow in itemreader:
if(itemrow["empid"]==emprow["empid"]):
output.append(itemrow)
empcount = empcount +1
print output
json.dump(output, jsonfile,sort_keys=True)
and it doesnot work. Help needed. Thanks