将Json转换为CSV

时间:2019-11-08 16:24:22

标签: python json file parsing export-to-csv

我有此格式的json,并且想要转换为CSV文件。

{
  "extrapolationLevel": 1,
  "columnNames": [
    "name",
    "usersession.country",
    "application",
    "usersession.osFamily",
    "usersession.startTime",
    "visuallyCompleteTime"
  ],
  "values": [
    [
      "pdp",
      "Serbia",
      "Desktop",
      "Windows",
      1573215462076,
      1503
    ],

  ]
}

我想将此json转换为CSV格式,这是我的脚本

import csv
import json

with open('response_1573222394875.json') as infile:
    Data = json.loads(infile.read())

with open("q.csv", "w") as outfile:
    f = csv.writer(outfile)
    f.writerow(["name","usersession.country","application","usersession.osFamily","usersession.startTime","visuallyCompleteTime"])
    f.writerow([Data["name"], Data["usersession.country"],
                Data["application"],
                Data["usersession.osFamily"],
                Data["usersession.startTime"],
                Data["visuallyCompleteTime"]])

预期输出

 name usersession.country application usersession.osFamilyusersession.startTime visuallyCompleteTime
      pdp      Serbia      Desktop      Windows      1573215462076      1503
      plp      us           APP           Windows      1573215462076      1548
    startpage  uk            Site         Windows      1573215462076      1639
      product  india      Desktop        Windows      1573215462076      3194
       pdp     Vietnam      APP         Windows        1573215462076      3299

有人可以在这里帮我吗?

2 个答案:

答案 0 :(得分:0)

Data的键分别为"extrapolationLevel""columnNames""values"。例如,Data["usersession.country"]没有任何意义,因为该键没有字典。值仅存储在列表中。这就是您需要做的所有事情:

with open("q.csv", "w") as outfile:
    f = csv.writer(outfile)
    f.writerow(Data["columnNames"])
    f.writerows(Data["values"])

答案 1 :(得分:0)

import json

json_str = '''
{
  "extrapolationLevel": 1,
  "columnNames": [
    "name",
    "usersession.country",
    "application",
    "usersession.osFamily",
    "usersession.startTime",
    "visuallyCompleteTime"
  ],
  "values": [
    [
      "pdp",
      "Serbia",
      "Desktop",
      "Windows",
      1573215462076,
      1503
    ]
  ]
}
'''

data = json.loads(json_str)

csv_row = lambda v: ('"{}",' * len(v)).format(*v)[:-1] # remove trailing comma

print(csv_row(data["columnNames"]))
for value in data["values"]:
    print(csv_row(value))