Python 如何通过JSON提要进行搜索
我正在使用下面的代码,调用GoogleMapsAPI并解析一些JSON数据Python 如何通过JSON提要进行搜索,python,json,google-maps,Python,Json,Google Maps,我正在使用下面的代码,调用GoogleMapsAPI并解析一些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.url
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
这个很好用。但是,我只需要['results']['address\u components']
中的值,其中'type'
是[“locality”,“political”]
但是,该值的索引根据给定邮政编码字符串的精确程度而有所不同
如果我给出一个直接的poscode(如XX10),该值将出现在地址\u组件
列表的第0项中。但是,如果我给出一个城市和邮政编码,它会出现在第一项中
谁能帮帮我吗。我需要在address\u组件中搜索[“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
(完整地址)
正如您在示例1中看到的,我要查找的数据在索引1中,而在第二个示例中,我要查找的数据在索引2中。从json创建一个对象,并通过键访问值
import json
obj = json.loads(jsonString)
这看起来像您想要的:) 关于and最酷的一点是,你不需要按数字编制索引,而是按名称编制索引。在这种情况下,您的对象(或至少是您关心的数据)会发生如下故障:
'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
]
}
]
}
]
您能在每种情况下发布一个JSON示例吗?顺便说一下,使用
requests.get('http://maps.googleapis.com/maps/api/geocode/json“,{'address':'%s','sensor':'false'}).json()
在我看来更合适。特别是如果您要为属性使用单独的变量<代码>导入请求显然是必需的。确认,否!JSON不是Python的一个子集,您也不希望在应用程序中评估其他人的内容json.loads
(由OP使用)是获取对象的正确方法。问题是关于如何从对象本身访问数据。我得到一个错误TypeError:result['address\u component']中address\u component的读取行上的字符串索引必须是整数:
whoops!我忘了关注结果!现在修好:)我想现在可以修好了。将result['address\u components']
更改为result['address\u components']
并将results
更改为googleResponse['results']
'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
]
}
]
}
]