我对 python 很陌生,我正在尝试从 csv 文件获取以下 JSON 输出,并且 csv 文件如下所示
date customer Ex employer emailID CIN CIN2 BatcheSource
9-Jul-24 ABC1 EmployerAnme1 [email protected] 123456 9087690,345678 payment
9-Oct-24 BCD1 EMP2 [email protected] 234566 adasd
我正在寻找的 JSON 输出是
[
{
"Cin":"123456",
"Date":"9-Jul-24",
"Ex Employer":"Employer Name 1",
"Batche Source":"Payment"
},
{
"Cin":"9087690",
"Date":"9-Jul-24",
"Ex Employer":"Employer Name 1"
"Batche Source":"Payment"
},
{
"Cin":"345678",
"Date":"9-Jul-24",
"Ex Employer":"Employer Name 1",
"Batche Source":"Payment"
},
{
"Cin":"234566",
"Date":"9-Oct-24",
"Ex Employer":"EMP2",
"Batche Source":"adasd"
}
]
到目前为止我尝试过的代码是这个,但我不确定如何获取逗号分隔的单元格多个值的新条目:
import csv
import json
with open('test.csv') as infile:
reader = csv.DictReader(infile)
out = [{"CIN": row['CIN'],"Date": row["Date"], "Ex Employer": row["Ex Employer"],"CIN2": row["CIN2"],"Batche Source": row["Batche Source"]} for row in reader]
with open('test1.json', 'w') as outfile:
json.dump(out, outfile)
使用熊猫
import pandas as pd
import json
result = pd.read_csv('my.csv')
csv_as_dict = result.to_dict(orient='records')
csv_as_json = json.dump(csv_as_dict)