'How to use variable in JMESPath expression?

The regular expression works perfect as below: jmespath.search(currentStats, 'Items[?Name == Annie]')

But I want to make my filtered key as a variable.

I have tried var name = "Annie" jmespath.search(JSONdata, 'Items[?Name == %s]' %name;)

Which does not work. Many thanks in advance.



Solution 1:[1]

There's no built-in way in jmespath or the search function to template values into the query string, but you can safely embed JSON literals with backticks, however your language allows it.

var name = "Annie";
var result = jmespath.search(JSONdata, 'Items[?Name == `' + JSON.stringify(name).replace('`','\\`') + '`]');

We need to convert the string to JSON, escape any backticks in that string and then wrap it in backticks. Let's wrap that into a function to make it a bit nicer to read:

function jmespath_escape(item) {
    return '`' + JSON.stringify(item).replace('`','\\`') + '`';
}

var name = "Annie";
var result = jmespath.search(JSONdata, 'Items[?Name == ' + jmespath_escape(name) + ']');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Caleb