【问题标题】:JQ map objects to arrayJQ 将对象映射到数组
【发布时间】:2021-12-10 09:02:56
【问题描述】:

我有这个输入数据:

[
  {
    "attributes": {
      "created": "2021-10-18T12:02:39+00:00",
      "enabled": true,
      "expires": null,
      "notBefore": null
    },
    "contentType": null,
    "id": "https://kjkljk./secrets/-/1",
    "managed": null,
    "name": "pw",
    "tags": {}
  },
  {
    "attributes": {
      "created": "2021-10-18T12:06:16+00:00",
      "enabled": true,
      "expires": null,
      "notBefore": null
    },
    "contentType": "",
    "id": "https://kjklj./secrets/-/2",
    "managed": null,
    "name": "pw",
    "tags": {}
  }
]

我需要使用 jq 将 id 值提取到启用设置为 true 的新数组中。这是我目前所拥有的:

.[] | select(any(.attributes; .enabled== true)) | {id} 

但它只会导致:

{
  "id": "https://kjkljk./secrets/-/1"
}
{
  "id": "https://kjklj./secrets/-/2"
}

我怎样才能把这两个对象变成一个字符串数组呢?

[
  "id": "https://kjkljk./secrets/-/1",
  "id": "https://kjklj./secrets/-/2"
]

【问题讨论】:

  • [ "id": "https://kjkljk./secrets/-/1", "id": "https://kjklj./secrets/-/2" ] 不是有效的 JSON。你说的是“字符串数组”,所以你的意思是[ "https://kjkljk./secrets/-/1", "https://kjklj./secrets/-/2" ]

标签: json bash jq


【解决方案1】:

使用map而不是.[]来保留数组:

map(select(any(.attributes; .enabled)) | {id})
[
  {"id": "https://kjkljk./secrets/-/1"},
  {"id": "https://kjklj./secrets/-/2"}
]

Demo

请注意,这会产生一个对象数组[{…},{…}],我相信这是您所要求的,尽管在您想要的输出中您缺少花括号{}。要改为创建“字符串数组”,请使用 .id 而不是 {id} 像这样

map(select(any(.attributes; .enabled)) | .id)
[
  "https://kjkljk./secrets/-/1",
  "https://kjklj./secrets/-/2"
]

Demo

(另外,您可以使用.enabled 代替.enabled == true

【讨论】:

    【解决方案2】:

    这应该可行:

    map(select(any(.attributes; .enabled == true)) | .id)
    

    解释:map() 函数不是用.[] 拆分数组,而是保持数组结构完整,但对元素进行操作。使用.id 而不是{id} 可以避免为每个选定值创建字典。

    如果我理解正确,您也可以将 any(.attributes; .enabled == true) 替换为 .attributes.enabled == true

    【讨论】:

      【解决方案3】:

      类似:

      $ jq '[.[] | select(.attributes.enabled) | .id]' input.json
      [
        "https://kjkljk./secrets/-/1",
        "https://kjklj./secrets/-/2"
      ]
      

      【讨论】:

        猜你喜欢
        • 2020-10-02
        • 2021-01-01
        • 2022-11-24
        • 1970-01-01
        • 2021-04-18
        • 2020-11-09
        • 2016-05-31
        • 2018-09-22
        • 2021-07-29
        相关资源
        最近更新 更多