Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get values from keys in JSON

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading