Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq - Get a higher level key after a selection

Tags:

json

select

key

jq

Given a JSON like the following:

{
  "data": [{
    "id": "1a2b3c",
    "info": {
      "a": {
        "number": 0
      },
      "b": {
        "number": 1
      },
      "c": {
        "number": 2
      }
    }
  }]
}

I want to select on a number that is greater than or equal to 2 and for that selection I want to return the values of id and number. I did this like so:

$ jq -r '.data[] | .id as $ID | .info[] | select(.number >= 2) | [$ID, .number]' in.json
[
  "1a2b3c",
  2
]

Now I would also like to return a higher level key for my selection, in my case I need to return c. How can I accomplish this?

like image 906
wesleydk Avatar asked Oct 20 '25 04:10

wesleydk


1 Answers

Assuming you want the string "c" instead of 2 in the output, this will work:

$ jq '.data[] | .id as $ID | .info | to_entries[] | select(.value.number >= 2) | [$ID, .key]' input.json
[
  "1a2b3c",
  "c"
]
like image 107
Shawn Avatar answered Oct 21 '25 19:10

Shawn



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!