我正在按以下格式将 CSV 文件转换为 JSON。CSV 文件:name, email, date, phonejohn, example.com, 26/11/18, 123john, hello.com, 12/08/18, 123456错误结果:[ { "name": "john", "email": "example.com", "items": [ { "phone": "example.com", "info": { "date": "example.com", } }, ] },]代码:primary_fields = ['name', 'email']primary_fields2 = ['date', 'phone']result = []with open('student.csv', 'r') as csv_ledger: r = csv.DictReader(csv_studemy) for row in r: d = {k: v for k, v in row.items() if k in primary_fields} d['items'] = [{'phone':v,'info': {'date':v}} for k, v in row.items() if k in primary_fields2] result.append(d)预期格式:[ { "name": "john", "email": "example.com", "items": [ { "phone": "123", "info": { "date": "26/11/18", } }, ] },]的k是报头和所述v假设BE值。结果,您可以看到所有行的值都将重复,并且它与标题不匹配。第二个循环,该值将复制date所有标题,依此类推。
1 回答
慕哥9229398
TA贡献1877条经验 获得超6个赞
Maximilian Peters 指出为什么您的代码在注释中不起作用。一般来说,我会避免所有这些并手动构建每个字典
import csv
result = []
with open("student.csv", "r") as csv_ledger:
for row in csv.DictReader(csv_ledger, skipinitialspace=True):
result.append({
"name": row["name"],
"email": row["email"],
"items": [{
"phone": row["phone"],
"info": {"date": row["date"]},
}],
})
这skipinitialspace=True是必要的,因为您发布的 csv 在每个逗号后都有空格。
添加回答
举报
0/150
提交
取消