I have a json that includes a dict and a list. I want to loop only the dict objects and stop the loop.
json_res = {
"abc": "123",
"Students": [
{
"Sub1": {
"Name":"Amit Goenka"
},
"Sub2": {
"Major":"Physics" ,
"Name2":"Smita Pallod"
},
"Sub3": {
"Major2":"Chemistry" ,
"Name3":"Rajeev Sen" ,
"Major3":"Mathematics"
}
},
[
[
"Name",
0,
"Student",
1
]
]
]
}
Here is what I tried:
for data in json_res['Students']:
val = data.get('Sub3')
this results:
{
"Major2":"Chemistry" ,
"Name3":"Rajeev Sen" ,
"Major3":"Mathematics"
}
and fails. I want to consider the loop only from "Sub1" till "Sub3".
CodePudding user response:
You need to add the isinstance to check for dict.
for data in json_res['Students']:
if isinstance(data, dict):
val = data.get('Sub3')
print(val)