JSON parsing with select

Hello! I get JSON like the following returned from a REST API:

{
“tasks” : [ {
“id” : “artifactory.VirtualCacheCleanupJob#9e6619bd-1864-4e1a-9fd7-8bb138813bf1”,
“type” : “org.artifactory.repo.cleanup.VirtualCacheCleanupJob”,
“state” : “scheduled”,
“description” : “Virtual Repositories Cache Cleanup”
}, {
“id” : “artifactory.ArtifactCleanupJob#63053617-894c-4099-a897-caf5b1a3abd2”,
“type” : “org.artifactory.repo.cleanup.ArtifactCleanupJob”,
“state” : “scheduled”,
“description” : “Remote Repositories Cached Artifacts Cleanup”
}, {
“id” : “artifactory.IntegrationCleanupJob#517e5d53-a183-4a18-abe4-b81e1136398d”,
“type” : “org.artifactory.repo.cleanup.IntegrationCleanupJob”,
“state” : “scheduled”,
“description” : “Integration/Snapshot Versions Cleanup”
} ]
}

“tasks” is a list, and I need to get the “state” of one of the entries in this list. I can’t depend on the list staying in this order so I can’t use an index to get the element I want. I can get the element I need in shell using a jq query:
jq ‘.tasks | select(.type == “org.artifactory.repo.cleanup.IntegrationCleanupJob”).state’

which gets the “state” for the specific type. Anyone know of an easy way to do this in ansible? I’m about to write a custom filter, but thought there might be a more concise way. I’d rather not use jq with the command module, although I guess I could do that too.

Thanks!
Guy

This is untested, but here is how to do that with jinja2 using built in filters:

(some_var|selectattr(‘type’, ‘equalto’, ‘org.artifactory.repo.cleanup.IntegrationCleanupJob’)|first)[‘state’]

selectattr always returns a generator/list.

http://jinja.pocoo.org/docs/dev/templates/#selectattr

http://jinja.pocoo.org/docs/dev/templates/#equalto

http://jinja.pocoo.org/docs/dev/templates/#first

Awesome!!!