在python中循环使用JSON

时间:2018-01-10 09:04:08

标签: python json loops

我是一个初学者,我正在尝试为一个课程创建一个程序,该程序将通过一个关于某些结果的数据集。我遇到了以下JSON中的所有团队的困难:

    {
      "name": "English Premier League 2014/15",
      "rounds": [
        {
          "name": "Matchday 1",
          "matches": [
            {
              "date": "2014-08-16",
              "team1": {
                "key": "manutd",
                "name": "Manchester United",
                "code": "MUN"
              },
              "team2": {
                "key": "swansea",
                "name": "Swansea",
                "code": "SWA"
              },
              "score1": 1,
              "score2": 2
            },
            {
              "date": "2014-08-16",
              "team1": {
                "key": "leicester",
                "name": "Leicester City",
                "code": "LEI"
              },
              "team2": {
                "key": "everton",
                "name": "Everton",
                "code": "EVE"
              },
              "score1": 2,
              "score2": 2
            }],
    }],
}

我使用了这些代码行:

for matchday in js['rounds'] :
    print(matchday['matches'][0]['team1']['name'])

这将打印每轮第一场比赛中第一支球队的名字,但我想打印每一轮所有第一支球队的名字。有人能给我一个暗示吗?

3 个答案:

答案 0 :(得分:3)

你应该添加第二个循环并迭代匹配:

for rounds in js['rounds']:
    for matches in rounds['matches']:
        print(matches['team1']['name'])

答案 1 :(得分:0)

你正在获取匹配列表中的第一项,只需再循环遍历列表,如

for matchday in js['rounds'] :
    match_day = matchday['matches']                 
    for each_match in match_day:           
        print(each_match['team1']['name'])

答案 2 :(得分:0)

for json_data in data['rounds']:
    for attribute, value in json_data.iteritems():
        print attribute, value