Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python3: Crawl JSon and Ignore Non-Existent Key

I’m parsing received JSon from an API and extract it’s values. Some API result don’t have certain keys, meanwhile the script is already hardcoded to extract the value from the missing key.

I have tried to handle exception on each value extraction. It’s try:except times and starts try:except all over the place:

#Example 1
if json_response['anoa']['pangea'].get('malaria'):
   print(json_response['anoa']['pangea']['malaria'])

#Example 2
try:
   print(json_response['anoa']['pangea']['malaria'])
except: pass

The thing with try:except over the entire extraction codes: it’s just breaks when got some exception and ignore the left-over code and starts from the beginning of loop. Yes, I feed data from a wordlist to the API using loops.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I also tried fuckitpy to ignore any exception but I wanted it to also print the exception and just continue.

with fuckit:
    my_shitty_parser

Using fuckitpy is also equivalent of try:except block but it cost less lines. I still fucking all over the place. Is there a better way to handle this? I need to extract a lot of key. It is sad to see the script just breaks over 1 unnecessary exception.

>Solution :

Instead of using json_response['anoa']['pangea'].get('malaria'), try json_response.get('anoa',{}).get('pangea',{}).get('malaria', None] because if you’re not guaranteed that anoa or pangea etc. exist, you’ll want to have a fallback in place for when they don’t. And to make sure your chains work as expected, make sure to match the fallback to the kind of data you were expecting. E.g. if it’s an object on the JSON side, use an empty dict as fallback, if it’s an array on the JSON side, use and empty list as fallback, etc.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading