jq

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:

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.