Filter a simple array with JMESPath
Asked Answered
W

1

10

I'm trying to filter a plain list I get from the Azure CLI, and am struggling to construct a query that filters the list properly. An example which encapsulates what I'm trying to accomplish would be trying to filter the list [1, 2, 3, 4, 5] and attempting to get all values greater than 2.

Using jq, I can do this like so: echo "[1, 2, 3, 4, 5]" | jq "map(select(. > 2))" giving [3, 4, 5 ]. The trouble comes from not being able to indicate the "current element" in JMESPath as far as I can tell, without having a particular key to refer to.

How would I go about filtering a simple list like this using a JMESPath query?

Wimple answered 17/1, 2019 at 17:30 Comment(0)
W
14

This can be done using the current node token @ as part of the filter expression. One note is that you must surround literals in JMESPath with backticks. Failure to do so results in an invalid expression. Here is the filter to get all numbers greater than two from an array:

[?@ > `2`]

For arrays of objects other than numbers you can use any of the built in functions in the filter expression along with the current node token @ to filter. This will get you all strings containing substring:

[?contains(@, `substring`)]
Wimple answered 18/1, 2019 at 13:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.