首页 > 解决方案 > 从嵌套的 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"
}

标签: pythonjson

解决方案


您应该将[{}]其设置为默认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"))

推荐阅读