使用 JQ 展平嵌套 JSON 数组

Ome*_*oni 7 json 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"
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我想展平内部数组 -.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"
      }
    ]
  }
Run Code Online (Sandbox Code Playgroud)

我能够使用以下 JQ 模式来展平内部 JSON 数组:

.site.alerts[] as $in | $in.instances[] as $h |  $in | del(.instances) as $in2 |  $h * $in2 
Run Code Online (Sandbox Code Playgroud)

这给了我一个非常接近的结果:

{
  "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"
}
Run Code Online (Sandbox Code Playgroud)

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

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

提前致谢!

Ini*_*ian 8

这真是一个很好的努力。你的想法是正确的,你已经确保.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
Run Code Online (Sandbox Code Playgroud)

jqplay.org - 网址

  • 太感谢了!这正是我所缺少的并且无法弄清楚的:) (2认同)