1

I have json dicts that I want to parse and get the values, but I get a key error as the dictionary doesn't exist. How can I pass on to the next loop.

The id =123 has the following json data

json_dict = {       
"ABC" :"qwe",
"Students": [
 { 
  "Sub1": {
   "Details": {
   "Custom": { 
   "Name":"Amit Goenka" 
     }
    }
   }
 }
}

The id =345 has the following json data

json_dict = {        
"ABC" :"qwe",
"Students": [
 { 
  "Sub1": {
   "Details": {
    }
   }
 }
}

My code:

id_l = ["123","345","324"]
for id in id_l:
  for data in json_dict['Students']:
       val = data.get('Sub1')
       val2 = data['Sub1']['Details']['Custom']
       if val2:
          print("Name exists")
       else:
         print("no Name")
         continue

I get Key error for ID = 345 as there is no "Custom" data.

user12
  • 19
  • 5

1 Answers1

0

You can check that a key exists in a dict using in. Your example would look something like this:

id_l = ["123","345","324"]
for id in id_l:
    for data in json_dict['Students']:
        val = data.get('Sub1')
        if 'Custom' in val['Details']:
            print("Name exists")
        else:
            print("no Name")
            continue

Also, note that data.get('Sub1') is similar to data['Sub1'], but it returns None if 'Sub1' is missing from data instead of raising a KeyError. Without additional error handling, this code will fail if 'Sub1' is missing from data.

Dallan
  • 504
  • 4
  • 13
  • I didn't think about using "custom" in if statement. Thanks, it works and it is good learning for me. Sorry I did not include the "Sub1" data, was more curious to the point I was missing. – user12 Mar 08 '22 at 08:46