我是Python和JSON的新手。
我从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"
]
}
]
}
我已经解析了
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'}]
我试图从这里提取两个字母的国家/地区代码(" US"):
Country: [{u'long_name': u'United States', u'types': [u'country', u'political'], u'short_name': u'US'}]
这是我的代码:
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
答案 0 :(得分:1)
所以你有print 'Country:', country
,
其中country= [{u'long_name': u'United States', u'types': [u'country', u'political'], u'short_name': u'US'}]
,所以这是一个元素的列表。
country[0]['short_name]'
应该为您提供'US'
如果您不希望country
成为列表,请不要在address_components
处对countryFull=address_components[5:6]
进行切片。仅在必要位置获取单个JSON对象。