2016-07-29 44 views
-3
{ 
    "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的json輸入中提取信息

蟒-c '進口JSON,SYS; OBJ = json.load(sys.stdin);打印 OBJ [ 「步驟」] ....'

我應該如何代碼打印步驟要打印已完成

+1

您已經擁有將JSON加載到Python對象的代碼。您只需遍歷該列表並查找該列表中的字典與您想要的名稱匹配即可。您已經解決了JSON加載部分;這是*只是一個Python列表與字典問題*。 –

回答

1

您可以輸入:

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

數據是你的數據結構。你會得到:

['COMPLETED'] 

這是一個元素的列表。

+0

我認爲它是[u'COMPLETED'] – Bharthan

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 
相關問題