基于其他字段的值从python中的json输入中提取信息

时间:2016-07-29 18:59:36

标签: python json

{
    "Steps": [
        {
            "Status": {
                "State": "PENDING",
                "StateChangeReason": {}
            },
            "ActionOnFailure": "CANCEL_AND_WAIT",
            "Name": "ABCD"
        },
        {
            "Status": {
                "State": "COMPLETED",
                "StateChangeReason": {}
            },
            "ActionOnFailure": "CANCEL_AND_WAIT",
            "Name": "KLMN"
        },
        {
            "Status": {
                "Timeline": {
                    "CreationDateTime": 1469815629.4289999
                },
                "State": "PENDING",
                "StateChangeReason": {}
            },
            "ActionOnFailure": "TERMINATE_CLUSTER",
            "Name": "XYZ"
        }
    ]
}

我想检查步骤的状态是否为" KLMN"完成与否。我怎么能在python中做到这一点。

  

python -c' import json,sys; obj = json.load(sys.stdin); print   OBJ ["步骤"] ....'

我应该如何编码打印步骤以打印COMPLETED

2 个答案:

答案 0 :(得分:1)

您可以输入:

[step['Status']['State'] for step in data['Steps'] if step['Name']=='KLMN']

数据是您的数据结构。你会得到:

['COMPLETED']

哪个是包含一个元素的列表。

答案 1 :(得分:1)

steps = {
    "Steps": [
        {
            "Status": {
                "State": "PENDING",
                "StateChangeReason": {}
            },
            "ActionOnFailure": "CANCEL_AND_WAIT",
            "Name": "ABCD"
        },
        {
            "Status": {
                "State": "COMPLETED",
                "StateChangeReason": {}
            },
            "ActionOnFailure": "CANCEL_AND_WAIT",
            "Name": "KLMN"
        },
        {
            "Status": {
                "Timeline": {
                    "CreationDateTime": 1469815629.4289999
                },
                "State": "PENDING",
                "StateChangeReason": {}
            },
            "ActionOnFailure": "TERMINATE_CLUSTER",
            "Name": "XYZ"
        }
    ]
}

if [step["Status"]["State"] for step in steps['Steps'] if step["Name"] == "KLMN"][0] == 'COMPLETED':
    #Do something