I got the JSON below:
JavaScript
x
61
61
1
{
2
"categories": [
3
{
4
"category_id": "1960",
5
"category_name": "England",
6
"competitions": [
7
{
8
"competition_id": "222",
9
"competition_name": "Premier League"
10
},
11
{
12
"competition_id": "203",
13
"competition_name": "League One"
14
},
15
{
16
"competition_id": "167",
17
"competition_name": "Championship"
18
},
19
{
20
"competition_id": "204",
21
"competition_name": "League Two"
22
},
23
{
24
"competition_id": "307",
25
"competition_name": "National League"
26
},
27
{
28
"competition_id": "693",
29
"competition_name": "FA Cup"
30
}
31
]
32
},
33
{
34
"category_id": "2007",
35
"category_name": "Spain",
36
"competitions": [
37
{
38
"competition_id": "14482",
39
"competition_name": "LaLiga"
40
},
41
{
42
"competition_id": "14982",
43
"competition_name": "LaLiga 2"
44
},
45
{
46
"competition_id": "989",
47
"competition_name": "Copa del Rey"
48
},
49
{
50
"competition_id": "38756",
51
"competition_name": "Primera Division RFEF"
52
},
53
{
54
"competition_id": "19477",
55
"competition_name": "Second Division B"
56
}
57
]
58
}
59
]
60
}
61
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
JavaScript
1
7
1
for key in categories:
2
competitions = key['competitions']
3
print(competitions)
4
for key in competitions:
5
competition_id = key['competition_id']
6
print(competition_id)
7
Advertisement
Answer
As @Barmar said, you need to run your inner loop inside of your outer loop:
JavaScript
1
7
1
for key in categories:
2
competitions = key['competitions']
3
print(competitions)
4
for key in competitions:
5
competition_id = key['competition_id']
6
print(competition_id)
7