Python 中 response.json() 的用途和使用方法
response.json() 是一个用于将响应对象 (response object) 中的 JSON 数据转换为 Python 字典或列表的方法。当使用 API 请求获取到的响应数据是 JSON 格式时,可以使用 response.json() 将其转换为 Python 中的数据结构,以便于在代码中进行处理和使用。
例如,假设您使用 Python 的 requests 库发送了一个 API 请求,并获得了以下 JSON 格式的响应:
{
'name': 'John Doe',
'age': 30
}
您可以使用 response.json() 方法将该 JSON 数据转换为 Python 字典:
import requests
response = requests.get('https://example.com/api/user')
user_data = response.json()
print(user_data['name']) # 输出: John Doe
print(user_data['age']) # 输出: 30
response.json() 方法为处理 API 响应中的 JSON 数据提供了方便快捷的方式,使您可以轻松地在 Python 代码中使用这些数据。
原文地址: https://www.cveoy.top/t/topic/hRTv 著作权归作者所有。请勿转载和采集!