📜  response.json() – Python请求

📅  最后修改于: 2022-05-13 01:55:31.932000             🧑  作者: Mango

response.json() – Python请求

response.json()返回结果的 JSON 对象(如果结果是以 JSON 格式编写的,否则会引发错误)。 Python请求通常用于从特定资源 URI 中获取内容。每当我们通过Python向指定的 URI 发出请求时,它都会返回一个响应对象。现在,此响应对象将用于访问某些功能,例如内容、标头等。本文围绕如何从响应对象中检查response.json()展开。它是请求模块中最常用的方法之一。

如何通过Python请求使用 response.json()?

为了说明 response.json() 的使用,让我们 ping geeksforgeeks.org。要运行此脚本,您需要在 PC 上安装Python和 requests。

先决条件:

  • 下载并安装Python 3 最新版本
  • 如何在Python中安装请求 – 适用于 windows、linux、mac

示例代码:

Python3
# import requests module
import requests
 
# Making a get request
response = requests.get('https://api.github.com')
 
# print response
print(response)
 
# print json content
print(response.json())


示例实现:

将上述文件另存为 request.py 并使用

Python request.py

输出:

response.json-Python-requests

检查终端输出的json 内容。它返回一个Python字典。

高级概念:

在Python中有很多库可以发出 HTTP 请求,它们有 httplib、urllib、httplib2、treq 等,但 requests 是其中最好的,具有很酷的特性。如果请求的任何属性显示为 NULL,请使用以下属性检查状态代码。

requests.status_code

如果 status_code 不在 200-29 范围内。您可能需要检查用于发出请求的方法开始 + 您请求资源的 url。