Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python将内容写回json文件?_Python_Json_Google Maps - Fatal编程技术网

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

如何使用python将内容写回json文件?,python,json,google-maps,Python,Json,Google Maps,我有一个json文件,看起来像 我的任务是读取地址,找到完整的特定地理代码,并更新回json文件。到目前为止,我能够做到以下几点: -->阅读jsonfile并将地址传递给GoogleAPI以获得准确的纬度和经度 我被困在这一点上,需要将读取的文件更新为新收到的准确纬度和经度 我的代码是: import json import requests import time import shutil import os from pprint import pprint def open_json

我有一个json文件,看起来像

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

-->阅读jsonfile并将地址传递给GoogleAPI以获得准确的纬度和经度

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

我的代码是:

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

将源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)

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

考虑以下示例,实现
写回\u cool\u 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}