So I am trying to work with an api currently which returns json data such as:
{
"emp1" : {
"EmpName" : "Chris Jackman",
"EmpAge" : "34",
"EmpGender" : "Male",
"EmpDept" : "IT",
"EmpDesg" : "Project Manager"
"EmpSal": {
"2019": 20000
"2020": 23000
},
"emp2" : {
"EmpName" : "Mary Jane",
"EmpAge" : "27",
"EmpGender" : "Female",
"EmpDept" : "IT"
}
}
Occasionally when we query the API one of these fields will be missing. When we try to access it
my_var = my_json["emp2"]["EmpDesg"]
Which will return a key error:
data_dict["EmpDesg"] = my_json["emp2"]["EmpDesg"]
KeyError: 'EmpDesg'
Is there a way to neatly deal with json paths missing rather than wrapping each field in a try catch:
try:
data_dict["EmpName"] = my_json["emp1"]["EmpName"]
except KeyError as e:
data_dict["EmpName"] = ""
try:
data_dict["EmpAge"] = my_json["emp1"]["EmpAge"]
except KeyError as e:
data_dict["EmpAge"] = ""
try:
data_dict["EmpGender"] = my_json["emp1"]["EmpGender"]
except KeyError as e:
data_dict["EmpGender"] = ""
try:
data_dict["salary"] = my_json["emp1"]["EmpSal"]["2020"]
except KeyError as e:
data_dict["salary"] = ""