Python parsing JSON



我尝试编写一个程序来提示输入位置,联系 Web 服务并检索 Web 服务的 JSON 并解析数据,并从 JSON 中检索第一个place_id。

import urllib
import json
import ssl
serviceurl = 'https://pr4e.dr-chuck.com/tsugi/mod/python-data/data/geojson?'
address = raw_input('Enter location: ')
url = serviceurl + urllib.urlencode({'sensor':'false', 'address': address})
print 'Retrieving', url
scontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
uh = urllib.urlopen(url, context=scontext)
data = uh.read()
print 'Retrieved',len(data),'characters'
try: 
    js = json.loads(str(data))
except: 
    js = None
if 'status' not in js or js['status'] != 'OK':
    print '==== Failure To Retrieve ===='
    print data

placeID = js['results'][0]['place_id']
print 'Place id: ', placeID

当我运行最后 2 行代码时,我偶然发现了这个错误。

Traceback (most recent call last):
File "<ipython-input-67-55fd9f9478fd>", line 1, in <module>
placeID = js['results'][0]['place_id']
KeyError: 'results'

你能帮我解决它吗!?为什么会这样?

然后你输入了一个不存在的位置,我想。当我运行代码时,它运行良好。这是我对有效位置Wayne State的输出:

Enter location: Wayne State
Retrieving https://pr4e.dr-chuck.com/tsugi/mod/python-data/data/geojson?sensor=false&address=Wayne+State
Retrieved 2280 characters

然后js['results'][0]['place_id']给了我:

u'ChIJ4Uny3H3vRYgRXPqO3llpGmg'

整个js如下所示:

{u'results': [{u'address_components': [{u'long_name': u'State Avenue',
     u'short_name': u'State Ave',
     u'types': [u'route']},
    {u'long_name': u'Wayne',
     u'short_name': u'Wayne',
     u'types': [u'locality', u'political']},
    {u'long_name': u'Union',
     u'short_name': u'Union',
     u'types': [u'administrative_area_level_3', u'political']},
    {u'long_name': u'Wayne County',
     u'short_name': u'Wayne County',
     u'types': [u'administrative_area_level_2', u'political']},
    {u'long_name': u'West Virginia',
     u'short_name': u'WV',
     u'types': [u'administrative_area_level_1', u'political']},
    {u'long_name': u'United States',
     u'short_name': u'US',
     u'types': [u'country', u'political']},
    {u'long_name': u'25570',
     u'short_name': u'25570',
     u'types': [u'postal_code']}],
   u'formatted_address': u'State Ave, Wayne, WV 25570, USA',
   u'geometry': {u'bounds': {u'northeast': {u'lat': 38.2407197,
      u'lng': -82.43612209999999},
     u'southwest': {u'lat': 38.2390583, u'lng': -82.4396787}},
    u'location': {u'lat': 38.2407197, u'lng': -82.43794009999999},
    u'location_type': u'GEOMETRIC_CENTER',
    u'viewport': {u'northeast': {u'lat': 38.24123798029149,
      u'lng': -82.43612209999999},
     u'southwest': {u'lat': 38.23854001970849, u'lng': -82.4396787}}},
   u'partial_match': True,
   u'place_id': u'ChIJ4Uny3H3vRYgRXPqO3llpGmg',
   u'types': [u'route']}],
 u'status': u'OK'}

当您使用无效位置运行它时(例如 stuff ),那么您没有密钥results js导致您得到的错误。这里是此方案的输出(仅第一行)(然后您只有键errorlocations导致您观察到的key error):

Enter location: stuff
Retrieving https://pr4e.dr-chuck.com/tsugi/mod/python-data/data/geojson?sensor=false&address=stuff
Retrieved 10041 characters
==== Failure To Retrieve ====
{
  "error":"Address not found in the list of available locations",
  "locations":[
    "AGH University of Science and Technology",
    "Academy of Fine Arts Warsaw Poland",
    "American University in Cairo",
    "Arizona State University",
    "Athens Information Technology",

因此,请确保选择有效位置列表中的位置。

最新更新