python - 从嵌套的 JSON 数据中获取特定值
问题描述
我使用以下代码获取日志条目,例如:
2020-01-11 17:47:16 [root] 信息:与电子邮件hunter@tomorrowworld.com 的联系已经存在。
我想知道是否.get("errors", {})[0].get('message')
是解决这个问题的正确方法?
if r.status_code != 200:
if r.json().get("error") == "CONTACT_EXISTS":
logging.info(r.json().get("errors", {})[0].get('message'))
完整的 JSON 响应:
{
"category": "OBJECT_ALREADY_EXISTS",
"correlationId": "4a3bf3a8-72c4-47ed-ac27-520ca0bac128",
"error": "CONTACT_EXISTS",
"errors": [
{
"in": "email",
"message": "A contact with email hunter@website.org already exists."
}
],
"identityProfile": {
"identity": [
{
"isPrimary": true,
"timestamp": 1578760232183,
"type": "EMAIL",
"value": "hunter@website.org"
},
{
"timestamp": 1578760232205,
"type": "LEAD_GUID",
"value": "79b14936-1215-454a-939d-42071b036bfb"
}
],
"isContact": true,
"linkedVid": [],
"savedAtTimestamp": 1578760232210,
"vid": 125401
},
"message": "Contact already exists",
"requestId": "2243a2d1ddd19d466ea4b98ab5cf6d66",
"status": "error"
}
解决方案
您应该将[{}]
其设置为默认errors
值以避免IndexError
.
您也可以提取json()
结果不解析响应内容两次:
if r.status_code != 200:
content = r.json()
if content.get("error") == "CONTACT_EXISTS":
logging.info(content.get("errors", [{}])[0].get("message"))
推荐阅读
- sql - 如何设置小时和分钟大于给定日期的日期?
- python - Python; 将矩阵转换为二值化版本(基数 2)
- c# - 如何使用 System.XAML 定义来自多个输入行的值在 C#/WPF 中注释 XAML 文件的一行
- php - 如果用户购买特定产品,将早期订单的订单状态更改为“已取消”
- openshift - openshift 容器平台内的服务可发现性
- asp.net - “跟随”功能的业务逻辑。并发问题
- c# - Winforms/WPF 互操作 - 调整嵌套用户控件的大小
- here-api - Here-API Incidents API prox ApplicationError/InvalidInputData
- javascript - 添加小时、分钟和秒的 JavaScript 代码
- tfs - 是否可以根据某些条件在 TFS 管道中运行步骤