如何使用Python循环遍历Json文件

时间:2017-04-15 13:29:48

标签: python json

我试图通过我下载的JSON文件使用python打印本赛季的所有顶级联赛赛程。这是我正在使用的Json文件的链接 - Json File

我设法使用while循环打印第一个比赛日的灯具。我想要约会,主队,“vs”,客场球队。我想我需要使用外部循环来循环其他比赛日,但我需要帮助。

import json
with open('en.1.json') as json_data:
    data = json.load(json_data)
    matchday = data['rounds'][0]['matches']
    i = 0
    while i < len(matchday):
        home = matchday[i]['team1']
        away = matchday[i]['team2']
        date =  matchday[i]['date']
        print date, home['name'], "vs", away['name']
        i = i + 1

1 个答案:

答案 0 :(得分:0)

以下是您遇到的问题的简单直观的解决方案:

with open(premierleaguedatafile) as data_file:
    # loads the entire dataset into a dictionary
    data = json.load(data_file) 

# get the list of all the rounds of fixtures
rounds = data['rounds']

# iterate over each round
for matchday in rounds:
    # store the list of matches played on this matchday
    matches = matchday['matches'] 

    # iterate over the matches to get individual match details
    for match in matches:
        match_date = match['date']
        home_team = match['team1']['name']
        away_team = match['team2']['name']
        print('{} {} vs {}'.format(match_date, home_team, away_team))