0
私はPythonとJSONを初めて使いました。JSONレスポンスからアイテムを抽出する
私はGoogle Maps APIから次の応答取得しています:私は2文字の国コード(「米国」)を抽出するためにしようとしている
{
"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'}]
を解析されてきましたここから:
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
ありがとうございました!ほんとうにありがとう! –