Python 中的 HTTP 请求和 JSON 解析

新手上路,请多包涵

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

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

它返回 JSON 格式 的结果。

我怎样才能在 Python 中做到这一点?我想发送这样的请求,接收结果并解析它。

原文由 Arun 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 729
2 个回答

我建议使用很棒的 请求 库:

 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

原文由 zeekay 发布,翻译遵循 CC BY-SA 4.0 许可协议

由于其内置的 JSON 解码器, requests Python 模块负责检索 JSON 数据并对其进行解码。这是取自 模块文档 的示例:

 >>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

因此,不必使用一些单独的模块来解码 JSON。

原文由 linkyndy 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题