I'm getting data from an API, and I want to validate if the data from it is there so i can use it without breaking the script. Currently I'm doing this with try blocks for each value. I'm wondering if there is a better way of writing this with DRY principles in mind.
for record in event['data']:
try:
name = record['entityDetail']['companySummary']['name']
nameObj = {
'name': 'name',
'value': name,
'type': 'S',
}
objExpression.append(nameObj)
except Exception as e:
error = 'Company Id:'+ id + ' property ' + str(e) + ' is not defined!'
print(error)
try:
brandCode = record['entityDetail']['companySummary']['brandCode']
brandCodeObj = {
'name': 'brandCode',
'value': brandCode,
'type': 'S',
}
objExpression.append(brandCodeObj)
except Exception as e:
error = 'Company Id:'+ id + ' property ' + str(e) + ' is not defined!'
print(error)
...