Python中的HTTP请求和JSON解析

时间:2011-06-17 13:17:44

标签: python json

我想通过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中执行此操作?我想发送这样的请求,收到结果并解析它。

8 个答案:

答案 0 :(得分:273)

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

答案 1 :(得分:119)

由于内置的​​JSON解码器,requests 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。

答案 2 :(得分:31)

requests内置了.json()方法

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

答案 3 :(得分:23)

import urllib
import json

url = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'
result = json.load(urllib.urlopen(url))

答案 4 :(得分:12)

使用请求库,非常打印结果,以便您可以更好地找到要提取的键/值,然后使用嵌套for循环来解析数据。在示例中,我逐步提取行车路线。

import json, requests, pprint

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'
)


data = requests.get(url=url, params=params)
binary = data.content
output = json.loads(binary)

# test to see if the request was valid
#print output['status']

# output all of the results
#pprint.pprint(output)

# step-by-step directions
for route in output['routes']:
        for leg in route['legs']:
            for step in leg['steps']:
                print step['html_instructions']

答案 5 :(得分:4)

试试这个:

import requests
import json

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

# Request data from link as 'str'
data = requests.get(link).text

# convert 'str' to Json
data = json.loads(data)

# Now you can access Json 
for i in data['routes'][0]['legs'][0]['steps']:
    lattitude = i['start_location']['lat']
    longitude = i['start_location']['lng']
    print('{}, {}'.format(lattitude, longitude))

答案 6 :(得分:0)

还可以在控制台上使用漂亮的Json:

 json.dumps(response.json(), indent=2)

可能使用带有缩进的转储。 (请导入json

答案 7 :(得分:0)

import requests并使用json()方法:

source = requests.get("url").json()
print(source)

或者您可以使用:

import json,urllib.request
data = urllib.request.urlopen("url").read()
output = json.loads(data)
print (output)