-1

I have a json file which looks like https://www.dropbox.com/s/raplkyl5le1rmh9/testDehil.json?dl=0

My task was to read the address and find the full specific geo-code and update back the json file. I am able to do the following till now:

--> Read the jsonfile and pass the address to Google API to get the exact latitute and longitude.

I am stuck at this point where i need to update the read file to the newly received exact latitude and longitude.

My code is :

import json
import requests
import time
import shutil
import os
from pprint import pprint

def open_json():
  with open('/home/nishant/Documents/Python/Gnitin/testDehil.json') as json_data:
     d = json.load(json_data)
     #json_data.close()
     #pprint(d) 
     for item in d: 
       a = item['address']['address']
       google_call(a)
       time.sleep(10)
     # EXTRACT THE address from each and pass it below: ## 



def google_call(add):
   address = add  #This needs to be run in loop
   api_key = "XXXXXXXXXXXXXXXXXXXXX"
   api_response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}'.format(address, api_key))
   api_response_dict = api_response.json()

   if api_response_dict['status'] == 'OK':
      latitude = api_response_dict['results'][0]['geometry']['location']['lat']
      longitude = api_response_dict['results'][0]['geometry']['location']['lng']
      print 'Latitude:', latitude
      print 'Longitude:', longitude
      write_back_cool_stuff(latitude,longitude)

def write_back_cool_stuff(lat,lon):
   ## How to write back to the json file with received lat and long ? 

if __name__ == '__main__':
   source = "/home/nishant/Documents/Python/Gnitin/testDehil.json"
   dest = "/home/nishant/Documents/Python/Gnitin/testDehil_clean.json" 
   shutil.copyfile(source,dest)
   open_json()
Nishant Singh
  • 3,055
  • 11
  • 36
  • 74

2 Answers2

1

Read the source JSON to a dictionary, then get the coordinates for each item (if possible) and add these coordinates (or unknown value (None)) as address properties. Save the updated data as JSON.

import os
import json
import time
import shutil
import requests


def add_coordinates(source, dest):
    with open(source, 'r') as file_object:
        json_data = json.load(file_object)

    for item in json_data:
        address = item['address']['address']
        latitude, longitude = google_call(address)

        # add latitude and longitude as address properties
        item['address']['latitude'] = latitude
        item['address']['longitude'] = longitude

        # save updated json_data
        with open(dest, 'w') as file_object:
            json.dump(json_data, file_object)

        time.sleep(10)


def google_call(address):
    api_key = "XXXXXXXXXXXXXXXXXXXXX"
    api_response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}'.format(address, api_key))
    api_response_dict = api_response.json()

    latitude = None
    longitude = None

    if api_response_dict['status'] == 'OK':
        latitude = api_response_dict['results'][0]['geometry']['location']['lat']
        longitude = api_response_dict['results'][0]['geometry']['location']['lng']

        print 'Latitude:', latitude
        print 'Longitude:', longitude

    return latitude, longitude


if __name__ == '__main__':
    source = "/home/nishant/Documents/Python/Gnitin/testDehil.json"
    dest = "/home/nishant/Documents/Python/Gnitin/testDehil_clean.json"
    shutil.copyfile(source, dest)
    add_coordinates(source, dest)
Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64
0

json encoded data consists of key-value pairs. The same structure can also be represented as a dictionary in python. If you have a dictionary, and want to serialize and store it to a file, you would use the dump function from the json module.

Consider the following example, implementing your write_back_cool_stuff function:

import json

def write_back_cool_stuff(lat, lon):
    # create a dictionary containing your key-value pairs
    data = {'lat': lat, 'lon': lon}
    # get a file handle for writing
    with open('data.json', 'w') as f:
        # dump json encoded data to the file
        json.dump(data, f)

it would be used like this:

write_back_cool_stuff(30.0, 50.0)

and the content of the file will contain:

{"lat": 30.0, "lon": 50.0}
Corey Goldberg
  • 59,062
  • 28
  • 129
  • 143