从JSON响应中提取项目

2024-05-07 15:08:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉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'}]

我试图从这里提取两个字母的国家代码(“美国”):

    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

Tags: nameurladdressjslocationcountryresultslong
1条回答
网友
1楼 · 发布于 2024-05-07 15:08:34

所以你有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成为一个列表,请不要在countryFull=address_components[5:6]处分割address_components。只在必要的位置获取单个JSON对象。你知道吗

相关问题 更多 >