首页 > 解决方案 > Python Error in extracting data from nested json

问题描述

I could not find any solution similar to my json structure in python in the forum, so asking a fresh help.

I am trying to extract the value of Latitude and Longitude from the file called geolocation.json which has the following structure

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

I am trying the following code to extract the latitude and longitude of the last data from the file and pass it to googleAPI for reverse geo-coding.

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)

The code works if I hard code the latitude and longitude instead of extracting them from file (removing entire json aspect). So the problem is in extraction.I am getting the error as--

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

With my limited Python knowledge, I am stuck.

标签: jsonpython-2.7geolocationmulti-layer

解决方案


你有一个嵌套字典。利用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

推荐阅读