使用jq基于对象中的键值从Array返回整个对象

时间:2016-07-13 16:26:38

标签: arrays json linux sorting jq

我有一个.json文件,我想通过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"
}

1 个答案:

答案 0 :(得分: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