Skip to content
Advertisement

Get values from keys in JSON [closed]

I got the JSON below:

{
  "categories": [
    {
      "category_id": "1960",
      "category_name": "England",
      "competitions": [
        {
          "competition_id": "222",
          "competition_name": "Premier League"
        },
        {
          "competition_id": "203",
          "competition_name": "League One"
        },
        {
          "competition_id": "167",
          "competition_name": "Championship"
        },
        {
          "competition_id": "204",
          "competition_name": "League Two"
        },
        {
          "competition_id": "307",
          "competition_name": "National League"
        },
        {
          "competition_id": "693",
          "competition_name": "FA Cup"
        }
      ]
    },
    {
      "category_id": "2007",
      "category_name": "Spain",
      "competitions": [
        {
          "competition_id": "14482",
          "competition_name": "LaLiga"
        },
        {
          "competition_id": "14982",
          "competition_name": "LaLiga 2"
        },
        {
          "competition_id": "989",
          "competition_name": "Copa del Rey"
        },
        {
          "competition_id": "38756",
          "competition_name": "Primera Division RFEF"
        },
        {
          "competition_id": "19477",
          "competition_name": "Second Division B"
        }
      ]
    }
  ]
}

How can I loop through the json using python to get the values of competition_id? I have tried using a for loop but it’s only giving competition id of premier league. Below is the code I wrote

for key in categories:
    competitions = key['competitions']
    print(competitions)
for key in competitions:
    competition_id = key['competition_id']
    print(competition_id)

Advertisement

Answer

As @Barmar said, you need to run your inner loop inside of your outer loop:

for key in categories:
        competitions = key['competitions']
        print(competitions)
        for key in competitions:
                 competition_id = key['competition_id']
                 print(competition_id)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement