【问题标题】:Using jq unique_by with arrays将 jq unique_by 与数组一起使用
【发布时间】:2021-09-05 01:12:50
【问题描述】:

我正在运行 jq 1.6。经过数小时尝试使用 unique_by 的不同方式的挫折后,我决定我不明白它在做什么,也没有找到与我的用例类似的示例

我将 curl 输出通过管道传输到 jq 并进行一些处理。然后我将输出通过管道传输到另一个 jq 以删除“子”数组中的重复项:

jq'. |= unique_by(.bound_to[].where_to)'

进入上述命令的输入如下所示。我只想要每个 bound_to 数组中的 1 个条目。如您所见,记录 2 和 3 有重复项,但 unique_by 不会删除它们。我是正确引用它还是应该使用不同的过滤器组合?

我没有收到任何错误,但输出中仍然有所有 bound_to 条目。

谢谢

~~ 输入到 JQ ~~

[{
  "location": "S24C2B1F1",
  "bound_to": [
    {
      "access_ids": [],
      "system_ssn": "",
      "where_to": 11
    }
  ],
  "description": null,
  "ipv4": "192.168.11.1",
  "id": "50011"
},
{
  "location": "S24C2B1F2",
  "bound_to": [
    {
      "access_ids": [],
      "system_ssn": "",
      "where_to": 3
    },
    {
      "access_ids": [],
      "system_ssn": "",
      "where_to": 3
    },
    {
      "access_ids": [],
      "system_ssn": "",
      "where_to": 3
    }
  ],
  "description": null,
  "ipv4": "10.10.3.254",
  "id": "60003"
},
{
  "location": "S48C1B2F1",
  "bound_to": [
    {
      "access_ids": [],
      "system_ssn": "",
      "where_to": 10
    },
    {
      "access_ids": [],
      "system_ssn": "",
      "where_to": 10
    }
  ],
  "description": null,
  "ipv4": "192.168.10.1",
  "id": "50010"
}
]

【问题讨论】:

    标签: arrays json unique jq


    【解决方案1】:

    据我所知,使用unique 可以轻松(也许是最容易)完成任务:

    map( .bound_to |= unique )
    

    【讨论】:

    • 谢谢。这确实完成了我试图用 unique_by 完成的事情。问题已解决。
    猜你喜欢
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 2017-03-19
    • 2015-10-05
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多