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

Question:

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
Asked By: DM Equinox

||

Answers:

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')
Answered By: Daweo
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.