'Improving error bypass method on keys in json
The current method I use is as follows and this amount of try except is making me very uncomfortable and without confidence in the quality of using this method:
for post_message in json_data['result']:
try:
message_text_1 = post_message['channel_post']['caption']
print('Image: ' + message_text_1)
except:
try:
message_text_2 = post_message['channel_post']['pinned_message']['text']
print('Pinned Message: ' + message_text_2)
except:
try:
message_text_3 = post_message['channel_post']['pinned_message']['text']
print('Basic Text: ' + message_text_3)
except:
pass
I tried using if not and elif not but it throws KeyError when it doesn't find the key instead of going to the next step:
for post_message in json_data['result']:
if not (post_message['channel_post']['caption'] is None):
message_text = post_message['channel_post']['caption']
print('Image: ' + message_text)
elif not (post_message['channel_post']['pinned_message']['text'] is None):
message_text = post_message['channel_post']['pinned_message']['text']
print('Pinned Message: ' + message_text)
elif not (post_message['channel_post']['pinned_message']['text'] is None):
message_text = post_message['channel_post']['pinned_message']['text']
print('Basic Text: ' + message_text)
And I also tried using except KeyError but besides it doesn't understand the first except, the second except is disabled:
for post_message in json_data['result']:
try:
message_text = post_message['channel_post']['caption']
print('Image: ' + message_text)
except KeyError:
message_text = post_message['channel_post']['pinned_message']['text']
print('Pinned Message: ' + message_text)
except KeyError:
message_text = post_message['channel_post']['pinned_message']['text']
print('Basic Text: ' + message_text)
What would be the most correct model to work with when there is more than a chance that the key does not exist in the JSON?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
