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?
JMESPath (JSON Matching Expression paths) is a query language for search JSON documents. It allows you to declaratively extract elements from a JSON document. XPath, for JSON. JMESPath includes: A formalized ABNF grammar.
JMESPath (pronounced “james path”) allows you to declaratively specify how to extract elements from a JSON document.
jq is typically used for the former, JMESPath for the latter. There's no reason why the remote service couldn't accept a jq filter, or that you couldn't use a JMESPath-based executable.
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`)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With