Home > Net >  Parse json dict results in Key-error - python
Parse json dict results in Key-error - python

Time:03-09

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.

CodePudding user response:

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.

  • Related