📜  python-json 8: 解析requrst的响应

📅  最后修改于: 2020-09-01 11:48:22             🧑  作者: Mango

我们使用requests库向服务器发送/上传数据时,一般情况下我们将获得JSON格式的响应。

GET请求的响应包含了我们称为有效负载的信息,通过解析返回的Json数据,我们可以获取这些信息,方便我们查看是否上传成功等。

我们可以使用Request的以下三种方法访问有效载荷(payload)数据。

  • response.content 用于访问原始字节格式的有效负载数据。
  • response.text:用于以String格式访问有效载荷数据。
  • response.json()用于访问JSON序列化格式的负载数据。

JSON响应内容

Request模块提供了一个内建JSON解码器,只需执行response.json(),其便以Python字典格式返回JSON响应,因此我们可以使用键值对访问JSON。

如果JSON解码失败,您将收到204错误。一般会返回一下两种异常:

  • 响应不包含任何数据。
  • 响应包含无效的JSON

与此同时:

解析JSON之前,您最好通过检查response.raise_for_status()或response.status_code,因为成功调用response.json()并不表示Request成功。比如:在HTTP 500错误的情况下,某些服务器可能依然后返回Json,其中包含了错误信息(例如,HTTP 500的错误详细信息)。

示例

执行GET调用, httpbin.org是一个Web服务,它允许测试请求并使用有关请求的数据进行响应。

import requests
from requests.exceptions import HTTPError

try:
    response = requests.get('https://httpbin.org/get')
    response.raise_for_status()
    # access JSOn content
    jsonResponse = response.json()
    print("Entire JSON response")
    print(jsonResponse)

except HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')
except Exception as err:
    print(f'Other error occurred: {err}')

print("Print each key-value pair from JSON response")
for key, value in jsonResponse.items():
    print(key, ":", value)

输出如下:

Entire JSON response
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': 'https://httpbin.org/get'}

Print each key-value pair from JSON response
args : {}
headers : {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}
origin : 49.35.214.177, 49.35.214.177
url : https://httpbin.org/get