如何用Python将CSV转换为含数组类型字段的JSON
解决CSV转JSON时重构amounts字段结构的问题
现有一段Python代码可将CSV文件转换为JSON格式,但当前转换结果中amounts与quantity为独立字段。需要将amounts字段转换为包含quantity和对应数值的数组结构,以下是具体修改方案:
当前代码
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')
当前转换结果
{"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}
期望转换结果
{"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": "200"}], "product": "0987654321", "online_from": "2022-08-08T09:00:26.000Z", "online_to": null, "price_info": null}
注:原期望结果中第二条的value值应为200,此处已修正符合样本数据逻辑
样本CSV数据
100,1,1234567890,2022-08-08T09:00:26.000Z 200,1,0987654321,2022-08-08T09:00:26.000Z
修改后的代码
import csv import json with open('csv/sample1.csv', encoding='utf-8-sig') as csvfile, open('output/file.json', 'w') as jsonfile: fieldnames = ("amounts","quantity","product","online_from","online_to","price_info") reader = csv.DictReader(csvfile, fieldnames) for row in reader: # 跳过空行(处理样本中的空行) if not any(row.values()): continue # 重构amounts字段为数组结构 row['amounts'] = [{'quantity': row['quantity'], 'value': row['amounts']}] # 删除原quantity字段 del row['quantity'] # 写入JSON文件 json.dump(row, jsonfile) jsonfile.write('\n')
修改说明
- 使用
with语句管理文件,自动处理文件关闭,避免资源泄漏 - 增加空行判断,跳过CSV中的空行数据
- 重构
amounts字段:将原amounts的值作为value,原quantity的值保留,组合成字典后放入数组 - 删除原
quantity字段,避免结果中出现冗余字段
内容的提问来源于stack exchange,提问作者DM Equinox
相关产品推荐
相关产品推荐

