Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting CSV to JSON with some keys that should be array using Python

Current Code Snippet

import csv
import json

csvfile = open('csv/sample1.csv', encoding='utf-8-sig')
jsonfile = open('output/file.json', 'w')

fieldnames = ("amounts","quantity","product","online_from","online_to","price_info")
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write('\n')

Current Result

{"amounts": "100", "quantity": "1", "product": "1234567890", "online_from": "2022-08-08T09:00:26.000Z", "online_to": null, "price_info": null}
{"amounts": "200", "quantity": "1", "product": "0987654321", "online_from": "2022-08-08T09:00:26.000Z", "online_to": null, "price_info": null}

Expected Result

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"amounts": [{"quantity": "1", "value": "100"}], "product": "1234567890", "online_from": "2022-08-08T09:00:26.000Z", "online_to": null, "price_info": null}
{"amounts": [{"quantity": "1", "value": "100"}], "product": "0987654321", "online_from": "2022-08-08T09:00:26.000Z", "online_to": null, "price_info": null}

Sample CSV Data

100,1,1234567890,2022-08-08T09:00:26.000Z

200,1,0987654321,2022-08-08T09:00:26.000Z

>Solution :

row is just plain dict, which you need to process before dump-ing, for example you might do it following way

...
for row in reader:
    amounts = row.pop('amounts')
    quantity = row.pop('quantity')
    row['amounts'] = [{'quantity': quantity, 'value': amounts}]
    json.dump(row, jsonfile)
    jsonfile.write('\n')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading