JSON parsing with select

187 views
Skip to first unread message

Guy Matz

unread,
Mar 28, 2016, 11:56:07 AM3/28/16
to ansible...@googlegroups.com
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

Matt Martz

unread,
Mar 28, 2016, 12:04:45 PM3/28/16
to ansible...@googlegroups.com
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.



--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To post to this group, send email to ansible...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/CABnTgtUHuRBgP4U%3Dt3hcRt29JWnyiMn0901Cb0ZcY2xxGBVt9g%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.



--
Matt Martz
@sivel
sivel.net

Guy Matz

unread,
Mar 28, 2016, 12:15:15 PM3/28/16
to ansible...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages