繁体   English   中英

使用JQ展平嵌套的JSON数组

[英]Flatten nested JSON array with JQ

我有以下格式的JSON:

{
  "@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模式吗?

提前致谢!

这是一个非常好的努力。 你的想法是正确的,你确保.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM