Search code examples
pythonurllib2

python 2.7 urllib2.Request KeyError


I'm successfully filling a json.load(response) request and able to navigate/see the result and appears to be what I am expecting. However, I'm getting a KeyError as I try to access attributes. In this instance I need to set a local variable to the "SHORT_NAME" attribute.

{u'fieldAliases': {u'SHORT_NAME': u'SHORT_NAME', u'OBJECTID': u'OBJECTID'}, u'fields': [{u'alias': u'OBJECTID', u'type': u'esriFieldTypeOID', u'name': u'OBJECTID'}, {u'alias': u'SHORT_NAME', u'length': 50, u'type': u'esriFieldTypeString', u'name': u'SHORT_NAME'}], u'displayFieldName': u'LONG_NAME', u'features': [{u'attributes': {u'SHORT_NAME': u'Jensen Beach to Jupiter Inlet', u'OBJECTID': 17}}]}

My python code to access the above:

reqAp = urllib2.Request(queryURLAp, paramsAp)
responseAp = urllib2.urlopen(reqAp)
jsonResultAp = json.load(responseAp) #all good here! above example is what this contains

#trying to set variable to the SHORT_NAME attribute
for featureAp in jsonResultAp['features']:
     aqp = feature['attributes']['SHORT_NAME']
     #this fails with: "KeyError: 'SHORT_NAME'"

It's obvious that "SHORT_NAME" is there so I'm not quite sure what I'm doing incorrectly.

Thanks for any feedback!


Solution

  • Change:

    aqp = feature['attributes']['SHORT_NAME']
    

    To:

    aqp = featureAp['attributes']['SHORT_NAME']