Python中的HTTP请求和JSON解析

307 投票
8 回答
968938 浏览
提问于 2025-04-16 19:46

我想通过谷歌的方向API动态查询谷歌地图。举个例子,这个请求是计算从伊利诺伊州的芝加哥到加利福尼亚州的洛杉矶的路线,中间经过密苏里州的乔普林和俄克拉荷马州的俄克拉荷马城这两个地方:

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来实现这个功能?我想发送这样的请求,接收结果并解析它。

8 个回答

50

requests库里有一个内置的 .json() 方法

import requests
requests.get(url).json()
171

requests是一个Python模块,它可以帮你获取JSON数据并且自动解码,因为它内置了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数据了。

503

我推荐使用非常棒的 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

撰写回答