2017-06-06 41 views
1

我很新的JQ,我試圖解析輸出JSON我從命令得到 -使用JQ分析JSON輸出以獲得特定性質的新的JSON輸出

aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE 

得到一個新的輸出其中密鑰的值與特定模式匹配。

例如,這是我從以前命令輸出JSON -

{ 
    "StackSummaries": [ 
    { 
     "StackId": "arn:aws:213dqwqwdqwdqwdq", 
     "StackName": "monkeyman", 
     "CreationTime": "2017-06-06T20:52:59.728Z", 
     "StackStatus": "CREATE_COMPLETE", 
     "TemplateDescription": "Liaison API ELB cloud formation script" 
    }, 
    { 
     "StackId": "arn:aws:csdfsdfcsdfsdfsdfsdfsdfgdfgfdg", 
     "StackName": "monkeyman2", 
     "CreationTime": "2017-06-06T20:51:55.191Z", 
     "StackStatus": "CREATE_COMPLETE", 
     "TemplateDescription": "yoohooo instance" 
    }, 
    { 
     "StackId": "arn:aws:sdffgds444fsdfsdfgdfgfdg", 
     "StackName": "starfish2", 
     "CreationTime": "2017-06-06T20:51:55.191Z", 
     "StackStatus": "CREATE_COMPLETE", 
     "TemplateDescription": "helloworld instance" 
    }, 
    { 
     "StackId": "arn:aws:csdfsdfcsdfsdfsdfsdfsdfgdfgfdg", 
     "StackName": "bulldog4", 
     "CreationTime": "2017-06-06T20:51:55.191Z", 
     "StackStatus": "CREATE_COMPLETE", 
     "TemplateDescription": "night night instance" 
    }, 
    { 
     "StackId": "arn:aws:yhyhyhyhyhysdfgdfgfdg", 
     "StackName": "carrotman", 
     "CreationTime": "2017-06-06T20:51:55.191Z", 
     "StackStatus": "CREATE_COMPLETE", 
     "TemplateDescription": "surprise mo instance" 
    } 

    ] 

} 

在這裏,我需要通過管道第一輸出,以便創建一個新的輸出JSON來JQ其中StackName startsWith monkeyman鬥牛犬和應該像 -

{ 
    "StackSummaries": [ 
    { 
     "StackId": "arn:aws:213dqwqwdqwdqwdq", 
     "StackName": "monkeyman", 
     "CreationTime": "2017-06-06T20:52:59.728Z", 
     "StackStatus": "CREATE_COMPLETE", 
     "TemplateDescription": "Liaison API ELB cloud formation script" 
    }, 
    { 
     "StackId": "arn:aws:csdfsdfcsdfsdfsdfsdfsdfgdfgfdg", 
     "StackName": "monkeyman2", 
     "CreationTime": "2017-06-06T20:51:55.191Z", 
     "StackStatus": "CREATE_COMPLETE", 
     "TemplateDescription": "yoohooo instance" 
    }, 
    { 
     "StackId": "arn:aws:csdfsdfcsdfsdfsdfsdfsdfgdfgfdg", 
     "StackName": "bulldog4", 
     "CreationTime": "2017-06-06T20:51:55.191Z", 
     "StackStatus": "CREATE_COMPLETE", 
     "TemplateDescription": "night night instance" 
    } 

    ] 

} 

我已經嘗試了很多,我能做到這一點在某種程度上使用基本的UNIX分裂和正則表達式的命令,但東西告訴我它禾使用jq直接做起來更容易,也更簡單。

+0

亞馬遜原生支持。我們不需要'jq'來實現這一點。請參閱此鏈接:http://opensourceconnections.com/blog/2015/07/27/advanced-aws-cli-jmespath-query/它解釋瞭如何實現此目的。 –

回答

2

容易JQ

jq '.[] |= map(select(.StackName | startswith("monkeyman"), startswith("bulldog")))' 

概括地說,圖(x)的適用x到被饋送到它的每一個對象。選擇(y)選擇滿足條件y的對象。在這種情況下,條件y是有一個名爲StackName的鍵,其值以「monkeyman」或「bulldog」開頭。

+0

這已經解決了我的問題,真棒。 – Shek