Alex_L Alex_L - 5 months ago 16
JSON Question

Extract an item from a JSON response

I'm new to Python and JSON.

I'm getting the following response from Google Maps API:

{
"status": "OK",
"results": [
{
"geometry": {
"location_type": "APPROXIMATE",
"bounds": {
"northeast": {
"lat": 40.73804080000001,
"lng": -73.5261501
},
"southwest": {
"lat": 40.6944609,
"lng": -73.5836571
}
},
"viewport": {
"northeast": {
"lat": 40.73804080000001,
"lng": -73.5261501
},
"southwest": {
"lat": 40.6944609,
"lng": -73.5836571
}
},
"location": {
"lat": 40.7179622,
"lng": -73.5535234
}
},
"address_components": [
{
"long_name": "11554",
"types": [
"postal_code"
],
"short_name": "11554"
},
{
"long_name": "East Meadow",
"types": [
"locality",
"political"
],
"short_name": "East Meadow"
},
{
"long_name": "Hempstead",
"types": [
"administrative_area_level_3",
"political"
],
"short_name": "Hempstead"
},
{
"long_name": "Nassau County",
"types": [
"administrative_area_level_2",
"political"
],
"short_name": "Nassau County"
},
{
"long_name": "New York",
"types": [
"administrative_area_level_1",
"political"
],
"short_name": "NY"
},
{
"long_name": "United States",
"types": [
"country",
"political"
],
"short_name": "US"
}
],
"place_id": "ChIJr-XSE-J9wokRJzSAdre-1i4",
"formatted_address": "East Meadow, NY 11554, USA",
"types": [
"postal_code"
]
}
]
}


And I have parsed out

lat 40.7179622 lng -73.5535234 LocType APPROXIMATE
East Meadow, NY 11554, USA
Country: [{u'long_name': u'United States', u'types': [u'country', u'political'], u'short_name': u'US'}]


I'm trying to extract the two-letter country code ("US") from here:

Country: [{u'long_name': u'United States', u'types': [u'country', u'political'], u'short_name': u'US'}]


This is the code I have:

import urllib
import json

serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?'

while True:
address = raw_input('Enter location: ')
if len(address) < 1 : break

url = serviceurl + urllib.urlencode({'sensor':'false', 'address': address})
print 'Retrieving', url
uh = urllib.urlopen(url)
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
continue

print json.dumps(js, indent=4)

lat = js["results"][0]["geometry"]["location"]["lat"]
lng = js["results"][0]["geometry"]["location"]["lng"]
locType = js["results"][0]["geometry"]["location_type"]
print 'lat',lat,'lng',lng,'LocType', locType
location = js['results'][0]['formatted_address']
print location
address_components=js["results"][0]["address_components"]
countryFull=address_components[5:6]
country=countryFull


print 'Country:', country

Answer

So you have print 'Country:', country,

where country= [{u'long_name': u'United States', u'types': [u'country', u'political'], u'short_name': u'US'}], so that is a list of one element.

country[0]['short_name]' should give you 'US'

If you don't want country to be a list, don't slice the address_components at countryFull=address_components[5:6]. Only get the single JSON object at the necessary position.

Comments