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,

3
  • can you try this: my_value_exist: "{{ my_json.json | json_query('contains(component.name,my_var)')}}" Commented Sep 4, 2017 at 15:05
  • Thanks for your answer. Commented Sep 4, 2017 at 15:27
  • the value exist in the json, but with this syntax the returned value is equal to false. my_value_exit should return true Commented Sep 4, 2017 at 15:27

2 Answers 2

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}}`'
Sign up to request clarification or add additional context in comments.

4 Comments

I found a solution with this task :
- 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
Post it as separate answer, please. But it's an overkill in my opinion.
helped me when trying to use a variable with json_query. thank you.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.