首页 > 解决方案 > 字符串对象在 python 代码中没有属性 get -error

问题描述

message=""
for action_result_dict in action_results:
            for k,v in action_result_dict.items():
                if k=="message":
                    message=v.get('message',"")

我编写了这段代码来获取消息的值,但它的抛出错误。字符串对象没有属性 get。任何人都可以指出错误吗?谢谢

[
    {
        "status": "failed",
        "data": [],
        "message": "",
        "parameter": {
            "vault_id": "45aaaecaacdcd45da1071e6c078",
            "force_analysis": true,
            "context": {
                "guid": "54381cf2-99fa-93e3f9ab4b48",
                "artifact_id": 0,
                "parent_action_run": []
            },
            "private": true
        },
        "summary": {}
    },
    {
        "status": "failed",
        "data": [],
        "message": "handle_action exception occurred",
        "parameter": {
            "vault_id": "45aaaecaacdc292ad45da1071e6c078",
            "force_analysis": true,
            "context": {
                "guid": "54381cf",
                "artifact_id": 0,
                "parent_action_run": []
            },
            "private": true
        },
        "summary": {}
    }
]

标签: python

解决方案


字符串没有get方法。也许你想使用get字典上的方法,action_result_dict.

message = None
for action_result_dict in action_results:
    message = action_result_dict.get("message", "")

如果您想要所有消息的列表,也许您可​​以这样做

messages = []
for action_result_dict in action_results:
    messages.append(action_result_dict.get("message", ""))

或者

messages = [action_result_dict.get("message", "") for action_result_dict in action_results]

推荐阅读