Python中的HTTP请求和JSON解析[重复]

iqjalb3h  于 2023-01-19  发布在  Python
关注(0)|答案(8)|浏览(173)
    • 此问题在此处已有答案**:

How can I parse (read) and use JSON?(5个答案)
What are the differences between the urllib, urllib2, urllib3 and requests module?(11个答案)
6小时前关门了。
我想通过Google Directions API动态查询Google Maps。例如,此请求计算从芝加哥(IL)到洛杉矶(CA)的路线,路线经过乔普林(MO)和俄克拉荷马城(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中我怎么做呢?我想发送这样的请求,接收结果并解析它。

gopyfrb3

gopyfrb31#

我推荐使用令人敬畏的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

pn9klfpd

pn9klfpd2#

由于内置了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。

lxkprmvk

lxkprmvk3#

requests具有内置的.json()方法

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

yshpjwxd4#

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

zc0qhyus5#

使用requests库,漂亮地打印结果,以便更好地定位要提取的键/值,然后使用嵌套的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']
j13ufse2

j13ufse26#

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

bsxbgnwa7#

试试这个:

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

y53ybaqx8#

对于控制台上的漂亮Json:

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

可以使用带缩进的转储。(请import json

相关问题