When do you use `json_query` versus `selectattr`/`map`?
AdvancedConceptJinja2, Conditionals and Loops
Answer
json_query (from community.general) uses JMESPath for complex queries on nested JSON, such as cloud API results. It needs the jmespath Python library on the controller.
running: "{{ ec2.instances | community.general.json_query('[?state.name==`running`].instance_id') }}"
Native filters (selectattr, map, selectattr('x','equalto',y)) need no extra dependency and are easier to debug. Use json_query when the structure is deeply nested or needs projection of several fields at once. Backticks mark literals in JMESPath, which is why quoting often goes wrong.
More on Jinja2, Conditionals and Loops
What role does Jinja2 play in Ansible?BeginnerWhat are the three Jinja2 delimiters?BeginnerShow a template with a loop and a conditional, and how it is deployed.BeginnerWhich filters do you use every day?BeginnerHow do you transform lists and dicts with filters (`map`, `select`, `selectattr`, `unique`, `flatten`)?IntermediateHow does `when` work and which operators can you use?Beginner