Anthony W Anthony W - 1 month ago 10x
Python Question

Python json key error

So I'm using the following simple snippet code to import a JSON object and then pull out specific fields into a list. Here it is:

#Set Observations URL request for all observations within the Osa Pennisula, Costa Rica
query = urllib2.urlopen("")
obSet = json.load(query)

#Find all common names for observations

for item in obSet['results']:
print item['taxon']['preferred_common_name']

The URL is a call to the iNaturalist
service. When I make the call I get the following result:

Red Brocket
Gumbo Limbo
Northern Tamandua
True Toads
Crested Owl
Tropical Screech-Owl
White-nosed Coati
Central American Squirrel Monkey
Thread-legged Bugs
Roadside Hawk
Barn Owl
Red Land Crab
Crested Caracar

KeyError Traceback (most recent call last)
<ipython-input-255-6e709d365b1b> in <module>()
4 for item in obSet['results']:
----> 5 print item['taxon']['preferred_common_name']

KeyError: 'preferred_common_name'

So it's odd - I know that the response has 304 results, but the code seems to print a few out and then blow up. Why is this?!


Because not every item in obSet['results'] has key item['taxon']['preferred_common_name'].

You can counteract that by catching these KeyErrors and printing the offensive keys. It also seems like some items have None as value for 'taxon' key, so you may want to catch these as well:

for item in obSet['results']:
          print item['taxon']['preferred_common_name']
     except (KeyError, TypeError):
          print item