I think this is close if not there:
It's always good to kkeep it simple
import os import csv import json def csv_to_json(): alldata = [] ddict = {} # Excpect input file in same directory as this script, so set cwd os.chdir(os.path.abspath(os.path.dirname(__file__))) with open('csvfile.csv') as fp, open('jsonfile.json', 'w') as fo: crdr = csv.DictReader(fp) for row in crdr: rnode = ddict = {} dnode = rnode['RecIds'] = {} dnode['type'] = 'A' dnode['value'] = row['A'] rnode['source'] = row['source'] rnode['status'] = row['status'] rnode['recordType'] = row['RecordType'] xnode = rnode['xIds'] = {} xnode['type'] = 'B' xnode['value'] = row['B'] alldata.append(ddict) json.dump(alldata, fo) def read_it_back_as_dict(): with open('jsonfile.json') as fp: mydict = json.load(fp) print(mydict) if __name__ == '__main__': csv_to_json() read_it_back_as_dict()results:
Output:[{
"RecIds": {
"type": "A",
"value": "q1"
},
"source": "Direct",
"status": "New",
"recordType": " Quote",
"xIds": {
"type": "B",
"value": ""}
},
{
"RecIds": {
"type": "A",
"value": "x1"
},
"source": "Direct",
"status": "New",
"recordType": " Quote",
"xIds": {
"type": "B",
"value": "y2"
}
}]
I think this is a way overly complicated json format and makes for extra work in deciphering.It's always good to kkeep it simple