【问题标题】:Look up information in a json string using Python使用 Python 在 json 字符串中查找信息
【发布时间】:2020-12-19 05:31:05
【问题描述】:

我尝试通过 Google Geocoding API 查找地址的经纬度。

我使用以下代码得到了 json 字符串:

address = "the Empire State Building" 
api_key = " " #not shown here
url = "https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s" % (address,api_key) 
response = requests.get(url) 
response_data = response.json()

字典response_data如下所示。

{'results': [{'address_components': [{'long_name': '20',
     'short_name': '20',
     'types': ['street_number']},
    {'long_name': 'West 34th Street',
     'short_name': 'W 34th St',
     'types': ['route']},
    {'long_name': 'Manhattan',
     'short_name': 'Manhattan',
     'types': ['political', 'sublocality', 'sublocality_level_1']},
    {'long_name': 'New York',
     'short_name': 'New York',
     'types': ['locality', 'political']},
    {'long_name': 'New York County',
     'short_name': 'New York County',
     'types': ['administrative_area_level_2', 'political']},
    {'long_name': 'New York',
     'short_name': 'NY',
     'types': ['administrative_area_level_1', 'political']},
    {'long_name': 'United States',
     'short_name': 'US',
     'types': ['country', 'political']},
    {'long_name': '10001', 'short_name': '10001', 'types': ['postal_code']}],
   'formatted_address': '20 W 34th St, New York, NY 10001, USA',
   'geometry': {'location': {'lat': 40.7484405, 'lng': -73.98566439999999},
    'location_type': 'ROOFTOP',
    'viewport': {'northeast': {'lat': 40.7497894802915,
      'lng': -73.98431541970848},
     'southwest': {'lat': 40.7470915197085, 'lng': -73.98701338029149}}},
   'place_id': 'ChIJaXQRs6lZwokRY6EFpJnhNNE',
   'plus_code': {'compound_code': 'P2X7+9P New York, NY, USA',
    'global_code': '87G8P2X7+9P'},
   'types': ['establishment',
    'museum',
    'point_of_interest',
    'tourist_attraction']}],
 'status': 'OK'}

接下来我应该采取哪些步骤来获取该地址的纬度和经度?

【问题讨论】:

    标签: python json google-geocoding-api


    【解决方案1】:

    当您运行print(type(response_data)) 时,它会返回dict

    如果是dict类,你可以使用dict方法.... 不幸的是,您想要的值在字典中的字典中的字典中的字典中的列表中。

    长话短说,试试

    latlong =  response_data['results'][0]['geometry']['location']
    print(latlong)
    

    更长的解释: “response_data”是一个字典,有 2 个键(您的信息存储在“结果”中)。 “结果”的值是一个列表,1 个条目(您的信息在索引 0 处)。 索引 0 处的值是一个 dict,有 6 个键(您的信息位于 key = 'geometry')。 'geometry' 的值是一个 dict,3 个条目(您的信息在关键的 'location' 处)。 'location' 的值是一个 dict,2 个条目(你的信息!!!'lat','lng')。

    【讨论】:

      猜你喜欢
      • 2013-05-20
      • 1970-01-01
      • 2014-03-26
      • 2017-09-26
      • 2015-01-16
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 2021-08-13
      相关资源
      最近更新 更多