我尝试编写一个程序来提示输入位置,联系web服务并检索web服务的JSON并解析数据,并从JSON中检索第一个位置的_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行代码时,我偶然发现了这个错误。在
^{pr2}$你能帮我修一下吗!?为什么会这样?在
然后你进入了一个不存在的地方,我想。当我运行代码时,它运行得非常好。以下是我对有效位置
Wayne State
的输出:然后
^{pr2}$js['results'][0]['place_id']
给了我:整个
js
如下所示:当您在一个无效的位置运行它时(例如}导致您观察到的
stuff
),那么您在js
中没有键results
,这会导致您得到错误。这里是这个场景的输出(仅仅是第一行)(然后只有键error
和{key error
):所以,一定要选择一个在有效位置列表中的位置。在
相关问题 更多 >
编程相关推荐