将复杂的分层JSON转换为CSV

时间:2018-12-07 04:37:20

标签: python json csv

我正在尝试通过JSON代码解析并将结果写入csv文件。 “名称”值应该是列标题,而“值”值是需要存储的值。这是我的代码。 CSV文件编写器不会使用逗号分隔字符串:eventIdlistingsvenueperformer,当我尝试执行以下操作时:header = col ['name'] +','我得到:eventId“,” listings“,” venue“,” performer而且它不是作为csv文件读取的,所以...我的问题是:我要这样做吗?怎么用逗号分隔字符串?

"results": [
    {
      "columns": [
        {
          "name": "eventId",
          "value": "XXXX",
          "defaultHidden": false
        },
        {
          "name": "listings",
          "value": "8",
          "defaultHidden": false
        },
        {
          "name": "venue",
          "value": "Nationwide Arena",
          "defaultHidden": false
        }]

这是我的代码:

json_decode=json.loads(data)
report_result = json_decode['results']
with open('testReport2.csv','w') as result_data:
    csvwriter = csv.writer(result_data,delimiter=',')
    count = 0
    for res in report_result:
        deeper = res['columns']
        for col in deeper:
            if count == 0:
                 header = col['name']
                 csvwriter.writerow([header,])
        count += 1

    for written in report_result:
        deeper =res['columns']
        for col in deeper:
            csvwriter.writerow([trouble,])
    result_data.close()

2 个答案:

答案 0 :(得分:0)

尝试以下代码:

json_decode=json.loads(data)
report_result = json_decode['results']
new_dict = {}
for result in report_result:
    columns = result["columns"]
    for value in columns:
        new_dict[value['name']] = value['value']

with open('testReport2.csv','w') as result_data:
    csvwriter = csv.DictWriter(result_data,delimiter=',',fieldnames=new_dict.keys())
    csvwriter.writeheader()
    csvwriter.writerow(new_dict)

答案 1 :(得分:-1)

尝试一下:

json_decode=json.loads(data)
report_result = json_decode['results']
with open('testReport2.csv','w') as result_data:
    csvwriter = csv.writer(result_data,delimiter=',')
    header = list(report_result[0]['columns'][0].keys())
    csvwriter.writerow(header)

    for written in report_result:
        for row in written['columns']:
            deeper =row.values()
            csvwriter.writerow(deeper)
    result_data.close()