dot*_*tty 3 python json google-maps
我正在使用下面的代码并调用Google Maps API并解析一些JSON数据.
def getLocalityFromPostCode(postcode):
import urllib, json
import pprint
url = "http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false" % postcode
googleResponse = urllib.urlopen(url)
jsonResponse = json.loads(googleResponse.read())
return jsonResponse
Run Code Online (Sandbox Code Playgroud)
这很好用.但是,我只需要从价值['results']['address_components'],其中'type'是 [ "locality", "political" ]但是,此值的指数不同,取决于给定的字符串邮编精确度如何.
如果我给出一个直的poscode(如XX10),该值将出现在address_components列表的第0项中.但是,如果我给一个城市和邮政编码它出现在第一项.
有谁可以帮助我吗.我需要在address_components中搜索该[ "locality", "political" ]值.
编辑
您可以在http://maps.googleapis.com/maps/api/geocode/json?address=sy4&sensor=false(只是邮政编码)和http://maps.googleapis.com/maps/api/geocode/json?address=47%20High%20Street%20Shrewsbury,%20SY4&sensor=false(完整地址)查看te feed .
正如您在示例1中看到的那样,我正在寻找的数据在索引1中,而在第二个示例中,我正在寻找的数据在索引2中.
这看起来像你想要的:)
results = json.load(googleResponse)['results']
for result in results:
for address_component in result['address_components']:
if address_component['types'] == ['locality', 'political']
# address_component['long_name'] and
# address_component['short_name'] are your data
break
Run Code Online (Sandbox Code Playgroud)
关于JSON和Python dicts的一个很酷的事情是你不需要按编号索引,你可以按名称索引.在这种情况下,您的对象(或至少您关心的数据)会像这样崩溃:
'results': # a list of resulting dicts
[
{ # one of those resulting dicts
'address_components': # a key, representing some other data
[ # which, in this case, is a list of address component dicts
{ # like this
'long_name': 'A String. The Long Name.'
'short_name': 'Another String. The Short Name.'
'types': # a list of type strings
[
'locality', # one of the types
'political' # the other type
]
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11565 次 |
| 最近记录: |