Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing select condition with jq's `IN`

Given the simplified input:

[
  [ "gpu" ],
  [ "disk" ]
]

I would like to select the arrays for which the first element is "gpu".

I can do it with a simple condition:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

map(select(.[0] == "gpu"))
[
  [ "gpu" ]
]

But I don’t understand what’s wrong when I try to use the IN builtin instead:

map(select(.[0] | IN(["gpu"])))
[]

I’m using jq 1.6

>Solution :

IN/1 is defined as def IN(s): any(s == .; .);, so map(select(.[0] | IN(["gpu"]))) translates to map(select(.[0] | any(["gpu"] == .; .))) but . inside the map is [ "gpu" ], thus .[0] is "gpu", which is not equal to [ "gpu" ], and the filter consequently fails.

Instead, compare .[0] with "gpu":

map(select(.[0] | IN("gpu")))
[
  [
    "gpu"
  ]
]

Demo

Using IN, however, only makes sense for compacting multiple comparisons. For this single comparison, of course, a simple map(select(.[0] == "gpu")) would suffice.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading