How to search through a JSON feed
I'm using the code below and make a call to the Google Maps API and parse some JSON data.
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
This works fine. However, i only need the value from['results']['address_components']
where the 'type'
is [ "locality", "political" ]
however, the index of this value differs depending on how precise the given postcode string is.
If i give a straight poscode (like XX10) the value appears in the 0th item in the address_components
list. However, if i give a city and postcode it appears in the 1st item.
Can someone help me please. I need to search through address_components for the [ "locality", "political" ]
value.
EDIT
You can view te feeds at http://maps.googleapis.com/maps/api/geocode/json?address=sy4&s开发者_StackOverflowensor=false
(just postcode) and http://maps.googleapis.com/maps/api/geocode/json?address=47%20High%20Street%20Shrewsbury,%20SY4&sensor=false
(full address).
As you can see in example 1 the data I'm looking for is in index 1, whereas in the second example the data I'm looking for is in index 2.
This looks like what you want :)
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
The cool thing about JSON and Python dicts is that you don't need to index by number, you index by name. In this case, your object (or at least the data you care about) breaks down like this:
'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
]
}
]
}
]
Create an object from the json and access the values by the keys
import json
obj = json.loads(jsonString)
精彩评论