Python:如何用优雅的方式解析Google API'address_components'

时间:2017-07-05 09:12:00

标签: python json google-maps

我的代码出了什么问题?

我正在从Google API检索JSON

我知道我可以做this way但我宁愿查看JSON并检索街道if i['types'] == 'street_number'

if response_data2['status'] == 'OK':
    Googleplace_id = response_data2['result']['place_id'] 
    Googleid = response_data2['result']['id'] 
    GoogleName = response_data2['result']['name']
    for i in response_data2['result']['address_components']:
        if i['types'] == 'street_number':
        street = i['long_name']     
    GoogleLatitude = response_data2['result']['geometry']['location']['lat']
    GoogleLongitude = response_data2['result']['geometry']['location']['lng']

Python说:UnboundLocalError: local variable 'street' referenced before assignment

1 个答案:

答案 0 :(得分:0)

解决方案是this

if response_data2['status'] == 'OK':
    Googleplace_id = response_data2['result']['place_id']
    Googleid = response_data2['result']['id']
    GoogleName = response_data2['result']['name']
    for types in response_data2['result']['address_components']:
        field = types.get('types', [])
        if 'street_number' in field:
            GoogleStreet_Number = types['long_name']
    GoogleLatitude = response_data2['result']['geometry']['location']['lat']
    GoogleLongitude = response_data2['result']['geometry']['location']['lng'] 

但这根本不优雅:(

必须要有类似

的方法
GoogleStreet_Number = response_data2['result']['address_components']['types' == 'street_number']['long_name']