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

Time:08-10

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

{"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

CodePudding user response:

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')
  • Related