Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQ map objects to array with condition

Tags:

json

bash

jq

I have this input data:

[
  {
    "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": {}
  }
]

I need to use jq to extract the id values into a new array where enabled is set to true. this is what I have so far:

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

but it only results in this:

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

how can i make these two objects into an array of strings instead?

[
  "id": "https://kjkljk./secrets/-/1",
  "id": "https://kjklj./secrets/-/2"
]
like image 545
dsfdsfsf Avatar asked Dec 21 '25 11:12

dsfdsfsf


1 Answers

Use map instead of .[] to retain the array:

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

Demo

Note that this produces an array of objects [{…},{…}], what I believe is what you asked for although in your desired output you are missing the curly object braces { }. To make an "array of strigs" instead, use .id instead of {id} like so

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

Demo

(Also, you can use .enabled instead of .enabled == true)

like image 112
pmf Avatar answered Dec 24 '25 01:12

pmf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!