jsonpython-2.7geolocationmulti-layer

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.


Solution

  • You have a nested dictionary. Use last_loc["data"]["coords"]

    Ex:

    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)
    

    Output:

    22.5757344
    88.4048656