我正在按以下格式将 CSV 文件转换为 JSON。
CSV 文件:
name, email, date, phone
john, example.com, 26/11/18, 123
john, 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所有标题,依此类推。
慕哥9229398
相关分类