python - Python 中的 HTTP 请求和 JSON 解析

我想通过 Google Directions API 动态查询 Google map 。例如,此请求计算从伊利诺伊州芝加哥到加利福尼亚州洛杉矶的路线,途经位于密苏里州乔普林和俄克拉荷马州俄克拉荷马市的两个航路点:

http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false

返回结果in the JSON format .

如何在 Python 中做到这一点?我想发送这样一个请求,接收结果并解析它。

最佳答案

我推荐使用很棒的 requests图书馆:

import requests

url = 'http://maps.googleapis.com/maps/api/directions/json'

params = dict(
    origin='Chicago,IL',
    destination='Los+Angeles,CA',
    waypoints='Joplin,MO|Oklahoma+City,OK',
    sensor='false'
)

resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below

JSON 响应内容:https://requests.readthedocs.io/en/master/user/quickstart/#json-response-content

https://stackoverflow.com/questions/6386308/

相关文章:

json - 使用 json.Unmarshal 与 json.NewDecoder.Decode

javascript - 如何使用 $.ajax 发送 JSON 而不是查询字符串?

json - 使用 Swift 读取 JSON 文件

json - 你如何表示一个 JSON 字符串数组?

ajax - POST JSON 失败,出现 415 Unsupported media type,

ios - Swift 3 URLSession.shared() 对成员 'dataTask(wi

json - 使用jq依次解析并显示一个json中的多个字段

json - 如何在 Node.js 中记录 JSON 对象的内容?

c# - 将列表序列化为 JSON

json - 在 mongodb 中使用 ISODate 进行日期查询似乎不起作用