Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a simple array with JMESPath

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?

like image 419
Marcus Avatar asked Jan 17 '19 17:01

Marcus


People also ask

What is 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.

What is JMESPath used for?

JMESPath (pronounced “james path”) allows you to declaratively specify how to extract elements from a JSON document.

Is JQ a JMESPath?

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.


1 Answers

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`)]
like image 68
Marcus Avatar answered Sep 28 '22 09:09

Marcus