如何使用python将内容写回json文件?

时间:2016-04-03 10:56:19

标签: python json google-maps

我有一个类似https://www.dropbox.com/s/raplkyl5le1rmh9/testDehil.json?dl=0

的json文件

我的任务是阅读地址并找到完整的特定地理代码并更新回json文件。到目前为止,我能够做到以下几点:

- >阅读jsonfile并将地址传递给Google API以获得准确的结果和经度。

我被困在这一点,我需要将读取文件更新为新接收的精确纬度和经度。

我的代码是:

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()

2 个答案:

答案 0 :(得分:1)

将源JSON读取到字典中,然后获取每个项目的坐标(如果可能)并将这些坐标(或未知值(None))添加为地址属性。将更新的数据保存为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)

答案 1 :(得分:0)

json编码数据由键值对组成。相同的结构也可以表示为python中的字典。如果您有字典,并希望序列化并将其存储到文件中,则可以使用dump模块中的json函数。

考虑以下示例,实现write_back_cool_stuff函数:

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)

它会像这样使用:

write_back_cool_stuff(30.0, 50.0)

并且文件的内容将包含:

{"lat": 30.0, "lon": 50.0}