我使用sendgrid api向用户发送电子邮件,然后检查状态,
res = requests.post(url)
print type(res)
并将类型打印为<class 'requests.models.Response'>
我得到了这个:
{
"message": "error",
"errors": [
"JSON in x-smtpapi could not be parsed"
]
}
我想从响应中仅获取message
值。我编写了以下代码但不起作用:
for keys in res.json():
print str(res[keys]['message'])
答案 0 :(得分:2)
你不需要循环;只需访问'message'
方法返回的字典上的response.json()
键:
print res.json()['message']
通过将response.json()
调用的结果存储在单独的变量中,可能更容易理解正在发生的事情:
json_result = res.json()
print json_result['message']
Postman API返回错误消息的原因是因为您的POST实际上并不包含任何数据;您可能想要向API发送一些JSON:
data = some_python_structure
res = requests.post(url, json=data)
当您使用json
参数时,requests
库会将其编码为JSON,并设置正确的内容类型标题。