2016-07-13 39 views
0

根據對象中的鍵值返回Array中的整個對象我有一個.json文件,如果該對象中的鍵值等於'failed',我想通過jq進行過濾以返回數組中的整個對象。我將如何做到這一點?使用jq

例JSON:

"version": "0.26.0", 
"controls": [{ 
    "id": "os-1.0", 
    "status": "passed", 
    "code_desc": "File /etc/profile content should match /umask\\s*022/", 
    "profile_id": "test" 
}, { 
    "id": "os-1.0", 
    "status": "passed", 
    "code_desc": "File /etc/bashrc content should match /umask\\s*022/", 
    "profile_id": "test" 
}, { 
    "id": "os-1.0", 
    "status": "failed", 
    "code_desc": "File /etc/csh.cshrc content should match /umask\\s*022/", 
    "profile_id": "test" 
    "message": "\nexpected: \"/sbin/sulogin\"\n  got: \n\n(compared using `cmp` matcher)\n" 
}] 

輸出到一個新的文件:

{ 
    "id": "os-1.0", 
    "status": "failed", 
    "code_desc": "File /etc/csh.cshrc content should match /umask\\s*022/", 
    "profile_id": "test" 
    "message": "\nexpected: \"/sbin/sulogin\"\n  got: \n\n(compared using `cmp` matcher)\n" 
} 
+0

你可以請嘗試https://github.com/stedolan/jq/wiki/Cookbook#filter-objects-based-on-the-contents-of-a-key –

+0

@BhavinSolanki這就是我試過的到目前爲止:cat file.json | jq -c'。[] |選擇(。控制|。和包含(「失敗」))'但我相信我缺少一個數組座標 – hedda

回答

1

文本顯示爲JSON是作爲JSON無效。假設它是固定有 以下篩選 將產生的結果如下圖所示的結構{"version": _, "controls": _},:

.controls[] | select(.status == "failed") 

輸出:

{ 
    "id": "os-1.0", 
    "status": "failed", 
    "code_desc": "File /etc/csh.cshrc content should match /umask\\s*022/", 
    "profile_id": "test", 
    "message": "\nexpected: \"/sbin/sulogin\"\n  got: \n\n(compared using `cmp` matcher)\n" 
} 

注:對於穩健性,你可能想使用.status?,而不是.status

+0

這工作,謝謝! – hedda