2016-06-30 10 views
0

저는 Python과 JSON을 처음 사용합니다.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 

답변

1

그래서 당신은 print 'Country:', country,

country= [{u'long_name': u'United States', u'types': [u'country', u'political'], u'short_name': u'US'}] 있습니다. 당신이 목록을 할 country을하지 않으려면

country[0]['short_name]'countryFull=address_components[5:6]address_components 슬라이스하지 않는 당신에게 'US'

를 제공해야합니다. 필요한 위치에 단일 JSON 객체 만 가져옵니다.

+0

감사합니다. 정말 감사! –