Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq: How to match one of array and get sibling value

Tags:

json

jq

I have some JSON like this:

{
  "x": [
    {
      "name": "Hello",
      "id": "211"
    },
    {
      "name": "Goodbye",
      "id": "221"
    },
    {
      "name": "Christmas",
      "id": "171"
    }
  ],
  "y": "value"
}

Using jq, given a name value (e.g. Christmas) how can I get it's associated id (i.e. 171).

I've got as far as being able to check for presence of the name in one of the array's objects, but I can't work out how to filter it down

jq -r 'select(.x[].name == "Christmas")'
like image 929
Peter Howe Avatar asked Dec 22 '17 10:12

Peter Howe


1 Answers

jq approach:

jq -r '.x[] | select(.name == "Christmas").id' file
171

The function select(boolean_expression) produces its input unchanged if boolean_expression returns true for that input, and produces no output otherwise.

like image 190
RomanPerekhrest Avatar answered Oct 18 '22 20:10

RomanPerekhrest