使用JQ将嵌套的JSON数组平铺

7

I have a JSON in the following format:

{
  "@version": "2.7.0",
  "site": {
    "@name": "http://api:9999",
    "@ssl": "false",
    "alerts": [
      {
        "pluginid": "10094",
        "desc": "<p>Base64 encoded data was disclosed by the application/web server<\/p>",
        "instances": [
          {
            "uri": "http://api:9999",
            "method": "POST",
            "evidence": "DxyPP_YQ6qdWA_Kw_ZLgYilIkXCz93Xs1CeJPvg"
          },
          {
            "uri": "http://api:9999",
            "method": "POST",
            "evidence": "eyJuYmYiOjE121lMWF1siSG9tZUFwcCJdfQ"
          }
        ],
        "count": "37"
      }
    ]
  }
}

我希望将内部数组 - .site.alerts.instances 扁平化,以便获取以下JSON:
{
    "@name": "http://api:9999",
    "@ssl": "false",
    "alerts": [
      {
        "pluginid": "10094",
        "desc": "<p>Base64 encoded data was disclosed by the application/web server<\/p>",
        "uri": "http://api:9999",
        "method": "POST",
        "evidence": "DxyPP_YQ6qdWA_Kw_ZLgYilIkXCz93Xs1CeJPvg",
        "count": "37"
      },
      {
        "pluginid": "10094",
        "desc": "<p>Base64 encoded data was disclosed by the application/web server<\/p>",
        "uri": "http://api:9999",
        "method": "POST",
        "evidence": "eyJuYmYiOjE121lMWF1siSG9tZUFwcCJdfQ",
        "count": "37"
      }
    ]
  }

我使用以下JQ模式可以将内部JSON数组压平:

.site.alerts[] as $in | $in.instances[] as $h |  $in | del(.instances) as $in2 |  $h * $in2 

这给了我一个非常接近的结果:
{
  "uri": "http://api:9999",
  "method": "POST",
  "evidence": "DxyPP_YQ6qdWA_Kw_ZLgYilIkXCz93Xs1CeJPvg",
  "pluginid": "10094",
  "desc": "<p>Base64 encoded data was disclosed by the application/web server</p>",
  "count": "37"
}
{
  "uri": "http://api:9999",
  "method": "POST",
  "evidence": "eyJuYmYiOjE121lMWF1siSG9tZUFwcCJdfQ",
  "pluginid": "10094",
  "desc": "<p>Base64 encoded data was disclosed by the application/web server</p>",
  "count": "37"
}

但并非完美的结果。这些对象不在数组中,并且来自父对象的字段,而这些字段不是数组的一部分(例如.site.@name)未被包括。

你能帮我改进我创建的JQ模式吗?

提前致谢!

1个回答

7

你的努力很不错。你的想法是正确的,你已经确保了.instances[]数组被展平,只需使用这个逻辑来重新构建所需的JSON即可。

jq '{ "@name" : .site."@name", 
      "@ssl"  : .site."@ssl", 
      "alerts": [.site.alerts[] as $in | $in.instances[] as $h | $in | del(.instances) as $in2 | $h * $in2 ]}' json

jqplay.org - URL


2
非常感谢!这正是我所缺失的,而且无法想出 :) - Omer Levi Hevroni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接