如何将这个数组转换成一个?

时间:2016-02-11 07:27:01

标签: json jq

我在https://jqplay.org/

玩jq

我目前拥有的JSON是:

{
  "license": {
    "type": "permissive",
    "url": "http://en.wikipedia.org/wiki/MIT_License",
    "name": "MIT"
  },
  "lib": "libxml2",
  "vuln-count": {
    "exact": 2,
    "total": 3,
    "historical": 1
  },
  "vulns": [
    {
      "exact": false,
      "timestamp-objects": [],
      "vuln": {
        "published-epoch": "1072839600",
        "cvss": 9.3,
        "summary": "libxml2, possibly before 2.5.0.\"",
        "published": "2003-12-31T03:00:00",
        "cve": "CVE-2003-1564",
        "modified": "2008-10-24T01:30:02",
        "modified-epoch": "1224811802"
      }
    },
    {
      "exact": true,
      "timestamp-objects": [
        "libxml2-2.8.0-1.x86_64.cpio:/usr/lib64/libxml2.so.2.8.0"
      ],
      "vuln": {
        "published-epoch": "1356061574",
        "cvss": 5,
        "summary": "libxml2 before 2.8.0 computes hash values.",
        "published": "2012-12-21T03:46:14",
        "cve": "CVE-2012-0841",
        "modified": "2014-01-28T02:42:55",
        "modified-epoch": "1390876975"
      }
    },
    {
      "exact": true,
      "timestamp-objects": [
        "libxml2-2.8.0-1.x86_64.cpio:/usr/lib64/libxml2.so.2.8.0"
      ],
      "vuln": {
        "published-epoch": "1346432101",
        "cvss": 6.8,
        "summary": "libxml2 2.9.0-rc1 and earlier.",
        "published": "2012-08-31T16:55:01",
        "cve": "CVE-2012-2871",
        "modified": "2014-01-28T02:45:36",
        "modified-epoch": "1390877136"
      }
    }
  ]
}

我目前的过滤器是

if .["vuln-count"].exact >0 
then {num_of_vulns: .["vuln-count"].exact, lib: .lib, license: .license.type, vuln: .vulns[]|select (.exact==true)|.vuln.cve} 
else empty end

结果是

{
  "num_of_vulns": 2,
  "lib": "libxml2",
  "license": "permissive",
  "vuln": "CVE-2012-0841"
}
{
  "num_of_vulns": 2,
  "lib": "libxml2",
  "license": "permissive",
  "vuln": "CVE-2012-2871"
}

为了获得以下输出,使用什么过滤器?

{
  "num_of_vulns": 2,
  "lib": "libxml2",
  "license": "permissive",
  "vulns": ["CVE-2012-0841", "CVE-2012-2871"]
}

感谢Santiago,这是工作过滤器:

if .["vuln-count"].exact >0  then {
   num_of_vulns: ."vuln-count".exact,
   lib: .lib,
   license: .license.type,
   vulns: .vulns | map(select(.exact).vuln.cve)
}  else empty end

1 个答案:

答案 0 :(得分:2)

您的预期结果作为JSON没有意义!在JSON对象上,属性键必须是唯一的。重复属性键时,JSON解析器通常只保留最后一个值,而忽略其余值。

但是,您可以获得以下内容:

{
  "num_of_vulns": 2,
  "lib": "libxml2",
  "license": "permissive",
  "vulns": ["CVE-2012-0841", "CVE-2012-2871"]
}

这是一个示例脚本(我省略了你的包裹if为空洞,但可以在它周围添加):

{
    num_of_vulns: ."vuln-count".exact,
    lib: .lib,
    license: .license.type,
    vulns: .vulns | map(select(.exact).vuln.cve)
}