5

I need to pass a variable in a json_query filter.

This example, with a fixed string, is working correctly (string=tutu) :

- set_fact:
 my_value_exist: "{{ my_json.json | json_query('contains(component.name,`tutu`)')}}"

But i need to pass a variable , instead of tutu

- set_fact:
 my_value_exist: "{{ my_json.json | json_query('contains(component.name,`{{my_var}}`)')}}"

{{my_var}} is a string retreived in a previous step

Do you have the correct syntax, so that the variable {{my_var}} could be passed correctly in parameter ?

Thanks for your help.

Regards,

dbo
  • 77
  • 2
  • 4

2 Answers2

11

Use helper variable for a task:

- set_fact:
    my_value_exist: "{{ my_json.json | json_query(qry) }}"
  vars:
    qry: 'contains(component.name,`{{my_var}}`'
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • I found a solution with this task : – dbo Sep 05 '17 at 09:21
  • - name: Does my value exists debug: var=item with_items: "{{ my_json.json | json_query(my_query)}}" vars: my_query: "contains(component.name,{{ my_var | to_json | replace ('\"',\"'\")}})" register: my_value_exist – dbo Sep 05 '17 at 09:21
  • Post it as separate answer, please. But it's an overkill in my opinion. – Konstantin Suvorov Sep 05 '17 at 09:30
  • helped me when trying to use a variable with json_query. thank you. – Jai Jan 08 '22 at 11:48
0

If you would like to avoid using a helper var you can use the second var directly by wrapping it in escaped double quotes ( \" ) between plus characters ( + ) like this:

- set_fact:
    my_value_exist: "{{ my_json.json | json_query('contains(component.name,`\" + my_var + \"`)') }}"

I know that this is a old question but it might help someone since this is the top result on the subject on google.

gardar
  • 75
  • 4