简体   繁体   中英

How to Pythonically check for errors in JSON response?

I have a response from an API which I need to save to a database and 99% of responses all are valid with the following details which I am formatting to be neater.

I've just had a 1% response break the code because there are no address['state'] so it returned a bool of False. I could do a try: except: for each line to catch it and if it's False but thought there must be a neater, more efficient way.

What's best practice in this instance when each line could be False?

order_id_newest = int(address['order_id'])
address_line_1 = address['line1'].title()
address_line_2 = address['line2'].title()
address_city = address['city'].title()
address_county = address['state'].title()
address_postcode = address['zip'].upper()

Add "" if that's sensible and ideally without several sets of try and except.


Well you could do this through dictionary's .get(key, default) method, like so:

address_county = address.get('state', '').title()


This will return an empty string '' in case address['state'] doesn't exist,
and address_county will be equal to '' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM