遍历 JSON 并转换为 CSV

我有以下 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"

    },


我想要的输出如下所示:

http://img2.mukewang.com/613c54d500017dd414340582.jpg

我写了以下脚本:


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。但是,我的脚本提供了以下输出:

http://img1.mukewang.com/613c54f30001d90416710096.jpg

我究竟做错了什么?是否也可以指定我想在 CSV 中包含哪些特定项目?


小怪兽爱吃肉
浏览 185回答 2
2回答

慕的地6264312

假设您将数据保存在名为 的变量中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())
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python