Python值与标头不匹配

时间:2019-01-13 17:46:22

标签: python json python-3.x

我正在将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应该是值。结果,您可以看到该值将在所有行中重复,并且与标题不匹配。第二个循环,该值将为所有标头复制date,依此类推。

1 个答案:

答案 0 :(得分:1)

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在每个逗号后都有空格。