GroovyScript - Extract specific number of attribute values from variable content response
Hey!
I've checked my groovy script notes which contains essentially all the groovy script snippets people have ever helped me with over the years - mostly from nmrao if I'm being honest - but I haven't got an example of what I need - sometimes I can expand the examples I already have to do what I need, but not this time.
I have a GET response JSON payload that can have 1 or many records in the response.
Each record in the response will have an 'id' attribute value (JSONPATH --> x.data[0].id)
The 'data' array can have 1 or many records, so JSONPATH for the id attribute value for first record this would be x.data[0].id, but there could be 50 records or more (50 records, the JSONPATH of the id associated with the 50th record would be x.data[49].id)
I won't need to save all 50, or 100, or however many records there will be.
I'd like to be able to specify the number of id values I save for later.
I want to save these 'id' values at TestSuite level for later.
I'm not sure how many 'id' values I'll need - maybe only 5 or maybe 10 - I don't know yet, so I'd like to be able to specify how many 'id' values I extract and save on the TestSuite.
This is the groovy script so far - as I say above - it's all courtesy of nmrao
//Script Assertion
def json = new groovy.json.JsonSlurper().parseText(context.response)
//find all 'id' attribute values
def id_list = json.data.'id'.findAll()
//List the 'id' attribute item count
log.info id_list.size
//Iterate thru each id, then stick them in a map, then once they're in a map, grab X instances of the 'id' values and split the map out and save them at TestSuite level
id_list.each { id ->
And that's as far as I've got.
I'm guessing I need to count the number of records so I don't try and grab more 'id' attribute values than actually exist causing the script to fail. I think I need a map and I've been googling - but it's beyond me - all the groovy script with maps I've got examples of, mix multiple methods together and I've never been able to read exactly what's occurring in those lines of the groovy. I know the groovy to save off a single property to TestSuite level for later use - but I don't know how to save off a variable sized number of attributes into separate properties for later use - especially as I'd like to grab a certain number of 'id' values from the total available - maybe from the first 10 records out of X returned.
I've attached the response payload that includes just a single record
Can anyone give me a steer please?
As always - I genuinely appreciate all/any help anyone can give me!
Cheers,
Rich