从嵌套json提取数据的Python错误

时间:2019-02-05 09:21:20

标签: json python-2.7 geolocation multi-layer

我在论坛中找不到与python的json结构相似的解决方案,因此寻求新的帮助。

我正在尝试从名为geolocation.json的文件中提取纬度和经度的值,该文件具有以下结构

{"userId":"Geo-data","data": {"mocked":false,"timestamp":1548173963281,"coords":{"speed":0,"heading":0,"accuracy":20.20400047302246,"longitude":88.4048656,"altitude":0,"latitude":22.5757344}}}

我正在尝试以下代码从文件中提取最后一个数据的纬度和经度,并将其传递给googleAPI进行反向地理编码。

import json
with open("geolocation.json") as geo_file:

   geo_dict = [json.loads(line) for line in geo_file]

for geo in geo_dict:
    last_loc= geo_dict[-1]

    geolat= str(last_loc['latitude'])
    geolong= str(last_loc['longitude'])

    #geolat = format(float(geo['latitude']),'.6f')
    #geolong = format(float(geo['longitude']),'.6f')


from geopy.geocoders import GoogleV3
#geolat='22.5757344'
#geolong='88.4048656'
latlong = [geolat, geolong]
val = ", ".join(latlong)
geolocator = GoogleV3(api_key='My_API_KEY')
locations = geolocator.reverse(val)
if locations:
    print(locations[0].address)

如果我对纬度和经度进行硬编码而不是从文件中提取它们(删除整个json方面),则该代码有效。所以问题出在提取上。我得到的错误是-

geolat= str(last_loc['latitude'])
KeyError: 'latitude'

以我有限的Python知识,我被困住了。

1 个答案:

答案 0 :(得分:1)

您有一个嵌套的字典。使用last_loc["data"]["coords"]

例如:

import json
last_loc = json.loads('{"userId":"Geo-data","data": {"mocked":false,"timestamp":1548173963281,"coords":{"speed":0,"heading":0,"accuracy":20.20400047302246,"longitude":88.4048656,"altitude":0,"latitude":22.5757344}}}')
geolat= str(last_loc["data"]["coords"]['latitude'])
geolong= str(last_loc["data"]["coords"]['longitude'])
print(geolat)
print(geolong)

输出:

22.5757344
88.4048656