-1

I have an array of objects with a tab_id and pane_id fields.

I would like to return the tab_ids of the first object whose pane_id field matches the value of an environment variable.

I am also interested in returning the tab_id of only the first match

Here is a sample file :

[
  {
    "tab_id": 0,
    "pane_id": 0,
  },
  {
    "tab_id": 0,
    "pane_id": 1,
  },
  {
    "tab_id": 0,
    "pane_id": 2,
  },
  {
    "tab_id": 1,
    "pane_id": 3,
  },
  {
    "tab_id": 2,
    "pane_id": 4,
  }
]

So in this case, if my environment variable is 2, I need the tab_id value of the object whose pane_id is 2, that is 0

cassepipe
  • 371
  • 6
  • 16
  • 5
    You'd be better off by providing a concrete example including a sample file, as currently it is, for example, underspecified what data types you are dealing with, what a "match" means in your case, etc. Filling in the gaps, you might be looking for something like `jq --arg fromenv "$envvar" 'first(.[] | select(.pane_id == $fromenv).tab_id)' input.json` – pmf Mar 25 '23 at 14:50
  • Consider the `--slurp` switch (load the full object graph - rather than operating on a stream) if you need to do any sorting before selecting the first item. – John Mar 25 '23 at 15:06
  • Does this answer your question? [Select objects based on value of variable in object using jq](https://stackoverflow.com/questions/18592173/select-objects-based-on-value-of-variable-in-object-using-jq) – knittl Mar 29 '23 at 05:52
  • @pmf Sorry,I used nushell in the end and I forgot about this question. But I still think an answer would be interesting for other people. Thanks for your answer. It looks like exactly what I need except it does not seem to work on the example input I added. Your solution almost works except for the environment variable part. It only works when I replace `$fromenv` directly with my variable's value else it does not work (I have of course replaced `$envvar` by the name of the variable I care about) – cassepipe Mar 30 '23 at 09:08

1 Answers1

1

Firstly, omit object-final commas (before closing an object with }) as it is not valid JSON.

Then, your provided example shows how important they are. It revealed that your values are numbers, not strings. Therefore you have to import the external values as such. In case of numbers, using --argjson is appropriate.

$ q=0
$ jq --argjson id "$q" 'first(.[] | select(.pane_id == $id).tab_id)' input.json
0
pmf
  • 24,478
  • 2
  • 22
  • 31