Jul-11-2020, 11:10 PM
(Jul-11-2020, 03:17 AM)Larz60+ Wrote: 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
Thank you for looking at this - I have really struggled to create this json - unfortunately it is part of an existing api that I want to interact with.
unfortunately does not quite generate expected format
"RecIds": [{ "type": "A", "value": "x1" }, { "type": "B", "value": "y2" }]RecIds can be one or more identifiers as per sample
Modding your example I can the basic structure but I encounter 3 problems:
- blank value(I guess and if can take care of this),
- invalid json due to the ' rather than "
- and the embedded objects should be [] rather than {}
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('sample.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'] dnode['type2'] = 'B' dnode['value2'] = row['B'] rnode['source'] = row['source'] rnode['status'] = row['status'] rnode['recordType'] = row['RecordType'] xnode = rnode['xIds'] = {} xnode['type'] = 'xA' xnode['value'] = row['xA'] xnode['type2'] = 'xB' xnode['value2'] = row['xB'] alldata.append(ddict) out=json.dumps(alldata, indent=4) f = open('jsonfile.json', 'w') f.write(out) 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()