使用json导入和导出csv

时间:2019-06-21 08:24:52

标签: python json csv

我想使用PTV API对GPS坐标进行反向地理编码。

我有经度和纬度,我想提供完整的地址。

我有一个脚本,可以逐行执行。我希望能够自动执行脚本并能够对csv文件进行地理编码并将结果导出到csv中。

由于我既没有掌握python也没有掌握json,因此无法适应该脚本。

import requests
from requests.auth import HTTPBasicAuth
import json


def main():
    # JSON Data
    payload = {
        "location": {
            "coordinate": {
                "point": {
                    "x": 2.35257,
                    "y": 48.83592
                }
            }
        },
        "options": [],
        "sorting": [],
        "additionalFields": [],
        "callerContext": {
            "properties": [
                {
                    "key": "Profile",
                    "value": "default"
                }
            ]
        }
    }

    jsonData = json.dumps(payload)
    header = {'content-type': 'application/json'}

    token = ''
    # Accessing the xServer internet API
    jsonresp = requests.post(
        url='http://localhost:50020/xlocate/rs/XLocate/findLocation', data=jsonData, headers=header, auth=HTTPBasicAuth('xtok', token))
    # In Python 3.5 use: 'resp = json.loads(str(jsonresp.text))

    resp = jsonresp.json()

    print(resp)
    for result in resp['resultList']:
        print(result['postCode'] + ';' + result['country'])


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

假设您能够读取/写入csv文件。

payload = {
        "location": {
            "coordinate": {
                "point": {
                    "x": 0,
                    "y": 0
                }
            }
        },
        "options": [],
        "sorting": [],
        "additionalFields": [],
        "callerContext": {
            "properties": [
                {
                    "key": "Profile",
                    "value": "default"
                }
            ]
        }
    }

results = []
# assuming the list below is coming from a csv file
geo_points = [[2.3,48.7],[2.56,47.12],[2.55,48.00]]
for point in geo_points:
    payload['location']['coordinate']['point']['x'] = point[0]
    payload['location']['coordinate']['point']['y'] = point[1]
    # now you can do the HTTP call and get the data from the server
    # keep the result in a list or dict so that by the end of the loop
    # you will be able to write it to csv