0

I am a total beginner and I am trying to create a program for a course that will go through a dataset about some results. I face a difficulty getting to all the teams in the following 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
            }],
    }],
}

I used these lines of code:

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

this will print the name of the first team from the first game of every round, yet I would like to print the name of all the first teams of every round. Could someone give me a hint?

Ankur Sinha
  • 6,473
  • 7
  • 42
  • 73
  • Try with a smaller example first. Also see: https://stackoverflow.com/questions/2733813/iterating-through-a-json-object – Christophe Roussy Jan 10 '18 at 09:06
  • You need an inner `for` loop through each `matchday["matches"]`. Note: in order to improve readability/consistency you should rename `matchday` to `round`. – CristiFati Jan 10 '18 at 09:09

3 Answers3

3

You should add second loop and iterate matches:

for rounds in js['rounds']:
    for matches in rounds['matches']:
        print(matches['team1']['name'])
Ivan
  • 2,463
  • 1
  • 20
  • 28
1

you are taking first item in the list of matches, just loop through the list again like,

for matchday in js['rounds'] :
    match_day = matchday['matches']                 
    for each_match in match_day:           
        print(each_match['team1']['name'])
Ivan
  • 2,463
  • 1
  • 20
  • 28
anandsp
  • 46
  • 7
0
for json_data in data['rounds']:
    for attribute, value in json_data.iteritems():
        print attribute, value