Python中的HTTP请求和JSON解析

2024-03-29 10:23:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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做这个?我想发送这样一个请求,接收结果并解析它。


Tags: comapijsonhttpgoogle地图动态路线
3条回答

由于内置的JSON解码器,^{}Python模块负责检索JSON数据和解码数据。以下是从the module's documentation中获取的示例:

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

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

我建议使用awesomerequests库:

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响应内容:http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content

^{}有内置的.json()方法

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

相关问题 更多 >