Python中的HTTP请求和JSON解析

Aru*_*run 177 python json

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

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

zee*_*kay 310

我建议使用awesome 请求库:

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
Run Code Online (Sandbox Code Playgroud)

JSON响应内容:http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content

  • 对我来说,我需要执行 `json=params` 而不是 `params=params` 否则我会收到 500 错误。 (4认同)

lin*_*ndy 129

requestsPython模块负责两个检索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/...
Run Code Online (Sandbox Code Playgroud)

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

  • 如果你需要与请求0.x(Debian wheezy)兼容,你应该使用`json.load()`或`json.loads()`,就像在0.x中一样,`json`是一个属性而不是一个功能. (4认同)
  • 如何从json响应'r'中仅提取特定的名称 - 值对? (3认同)
  • @nyuszika如果您正在使用debian,如果可能的话,使用pip来获取更新的python库.您不希望使用旧的python库进行编码,除非有一个重要的原因要使用debian在apt存储库中的内容. (2认同)

小智 35

requests有内置的.json()方法

import requests
requests.get(url).json()
Run Code Online (Sandbox Code Playgroud)


cly*_*ish 24

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))
Run Code Online (Sandbox Code Playgroud)

  • 它是Python 3中的`urllib.request`. (3认同)
  • 感谢您的帮助,但需要注意以下几点:在Python 3.0中删除了urllib.urlopen()函数,转而使用urllib2.urlopen(). (2认同)
  • Arun,是的,但它不再被命名为urllib2 (2认同)

Mic*_*ael 13

使用请求库,非常打印结果,以便您可以更好地找到要提取的键/值,然后使用嵌套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']
Run Code Online (Sandbox Code Playgroud)

  • @AlexStarbuck`import pprint`然后 - >`pprint.pprint(step ['html_instructions'])` (3认同)

mam*_*mal 13

只是import requests并使用 fromjson()方法:

source = requests.get("url").json()
print(source)
Run Code Online (Sandbox Code Playgroud)

或者你可以使用这个:

import json,urllib.request
data = urllib.request.urlopen("url").read()
output = json.loads(data)
print (output)
Run Code Online (Sandbox Code Playgroud)


Rag*_*pta 5

尝试这个:

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))
Run Code Online (Sandbox Code Playgroud)