Python json key error
<p>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:</p>

<pre><code>#Set Observations URL request for all observations within the Osa Pennisula, Costa Rica
query = urllib2.urlopen("http://api.inaturalist.org/v1/observations?nelat=8.60586&amp;nelng=-83.44410&amp;swlat=8.43066&amp;swlng=-83.74073&amp;per_page=1000&amp;order=desc&amp;order_by=created_at")
obSet = json.load(query)

#Find all common names for observations


for item in obSet['results']:
   print item['taxon']['preferred_common_name'] 
</code></pre>

<p>The URL is a call to the iNaturalist <code>node.js</code> service. When I make the call I get the following result:</p>

<pre><code>Red Brocket
Gumbo Limbo
Northern Tamandua
Colubrids
Bats
Skippers
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)
&lt;ipython-input-255-6e709d365b1b&gt; in &lt;module&gt;()
     3 
     4 for item in obSet['results']:
     ----&gt; 5     print item['taxon']['preferred_common_name']
     6 
     7 

KeyError: 'preferred_common_name'
</code></pre>

<p>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?! </p>

<p>Because not every item in <code>obSet['results']</code> has key <code>item['taxon']['preferred_common_name']</code>.</p>

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

<pre><code>for item in obSet['results']:
     try:
          print item['taxon']['preferred_common_name']
     except (KeyError, TypeError):
          print item
</code></pre>

python json