Forum Discussion

richie's avatar
richie
Community Hero
11 months ago

Re: GroovyScript - Extract specific number of attribute values from variable content response

Hey nmrao 

Ok - I'm still struggling - if I'm understanding the code correctly - your code starts off as follows via a Script Assertion:

def json = new groovy.json.JsonSlurper().parseText(context.response)
log.info json

def startingIndex=0

//Set this value, how many values to be stored 
def endIndex=4 

assert endIndex <= range.size(), 'Choose the endIndex less than list size' 

//Now get the sub list from original list 
def mySubList = range.subList(startingIndex,endIndex) 
log.info mySubList

//In order to save data as custom property, coierce it to String
def mySubListToString = mySubList.join(',')
log.info mySubListToString //Save this at suite level

so the JSONPATH of the first route_code out of the 4 I care about is  x.json.data[0].route_code

HOW do I match the startingIndex variable (which you've got declared above) to json.data[0].route_code) so that the other 3 route_code values (with values json.data[1].route_code, json.data[2].route_code, json.data[3].route_code) are extracted also?

Your comment on the line declaring the mySubListToString variable is the bit where I save my data as a custom testsuite property - but at this point I've got no data - I haven't yet extracted the x number of route_codes (4 in the case of the above script defined by the endIndex variable) - this is the bit I'm struggling with.

 

Just so you know I'm not just letting you do all the heavy lifting without trying to solve myself - I did try playing around with the following to see if I could get a little further along (or at least increase my understanding) - cos the code below is based on what you've helped me out with before - I was hoping I could edit it to do what I need, but it only logs the first instance of the route_code value - I thought lines 5 & 6 might extract all the route_codes - but I realised I'm not using the it() method - I did try adding .it() in various places but I couldn't get it to work - I really need to buy a groovy for dummies book!

// Log the first route_code
log.info('First (index zero) route_code = ' + json.data[0].route_code)

// Log all route_codes
json.data.every{ prop ->
	log.info('route_code = ' + prop.route_code) 
}

// Log all route_code with index
json.data.eachWithIndex(){ prop, idx ->
	log.info('route_code ' + idx + ' = ' + prop.route_code)
}

Been years since I've used ReadyAPI! when you were helping me with my groovy before and it's really showing!

As always - appreciate your help!

Cheers,

Rich