HenryDev HenryDev - 1 year ago 104
JSON Question

How to get ID's from JSON array in groovy using the each method?

I'm trying to get a list of ID's from a JSON array in Groovy. I know how to get the ID's using the regular FOR loop, but I would like to know how to do the same with the each method. I'm not sure how to implement that. Does anyone have any idea?
Thank you in advance. Here's my code that works just fine using the regular for loop. However I would like to do it with the each method.

import groovy.json.*

def restresponse = '[{"id":5, "name":"Bob"},{"id":8, "name":"John"},{"id":12, "name":"Jim"},{"id":20, "name":"Sally"}]'
def json = new JsonSlurper().parseText(restresponse)
def myListOfIDs = []

for (int i = 0; i < json.size; i++) {
myListOfIDs.add(json[i].id) // getting all ID's for each SourceSystem
log.info(myListOfIDs) // This prints out all this IDs

Answer Source

The shortest way to perform this "conversion" is by using the Groovy's Collection collect method, e.g.:

def myListOfIDs = json.collect { ele -> ele.id }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download