为了账号安全,请及时绑定邮箱和手机立即绑定

遍历 JSON 并转换为 CSV

遍历 JSON 并转换为 CSV

小怪兽爱吃肉 2021-09-11 15:03:00
我有以下 JSON 对象:{  "h": [    {      "id": "242611",      "minute": "2",      "result": "MissedShots",      "X": "0.9359999847412109",      "Y": "0.534000015258789",      "xG": "0.1072189137339592",      "player": "Ari",      "h_a": "h",      "player_id": "2930",      "situation": "OpenPlay",      "season": "2018",      "shotType": "Head",      "match_id": "9071",      "h_team": "FC Krasnodar",      "a_team": "Ural",      "h_goals": "2",      "a_goals": "0",      "date": "2018-12-02 11:00:00",      "player_assisted": "Wanderson",      "lastAction": "Chipped"    },我想要的输出如下所示:我写了以下脚本:def scrap_understat():    csv_file_path = currentDir + '/output_shots' + current_time + '.csv'    file = None    writer = None    file = io.open(csv_file_path, 'w', newline='', encoding='ISO-8859-1')    writer = csv.writer(file)    writer.writerow(        ['ID', 'Result', 'X', 'Y', 'xG', 'Player', 'Home/Away', 'Player_ID', 'Situation', 'Season', 'Shot_Type',         'Match_ID', 'xG', 'Home_Team', 'Away_Team', 'Home_Goals', 'Away_Goals', 'Date', 'Player_Assisted', 'Last_Action'])    for i in range(10096, 10097):       try:           driver.get('https://understat.com/match/' + str(i))           time.sleep(1)           if try_find_Element(driver, By.CLASS_NAME, 'error-code') is not None:               continue           shots = driver.execute_script("return shotsData")           for v in shots.items():               writer.writerow(v)变量shot给了我包含的 JSON 对象。我不想要键h和a。但是,我的脚本提供了以下输出:我究竟做错了什么?是否也可以指定我想在 CSV 中包含哪些特定项目?
查看完整描述

2 回答

?
慕的地6264312

TA贡献1817条经验 获得超6个赞

假设您将数据保存在名为 的变量中data:


data = {

  "h": [

    {

      "id": "242611",

      "minute": "2",

      "result": "MissedShots",

      "X": "0.9359999847412109",

      ....

写完标题后试试这个循环:


for items in data.values():

  for item in items:

    writer.writerow(item.values())


查看完整回答
反对 回复 2021-09-11
  • 2 回答
  • 0 关注
  • 159 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信