【问题标题】:Flatten nested JSON array with JQ使用 JQ 展平嵌套的 JSON 数组
【发布时间】:2018-07-24 00:51:23
【问题描述】:

我有一个格式如下的 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 模式吗?

提前致谢!

【问题讨论】:

    标签: json jq


    【解决方案1】:

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

    【讨论】:

    • 非常感谢!这正是我所缺少的,无法弄清楚:)
    猜你喜欢
    • 2016-09-29
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 2017-12-15
    • 2022-01-13
    相关资源
    最近更新 更多