Getting error with dynamic extractions in Groovy script
Hello,
In Groovy Script trying to extract value from API Response . Instead of getting first value in Json trying to extract dynamically by referring to its value from datasource.
Ex- def sourceId = context.expand( '${GetSources#Response#$[0][\'SourceId\']}' )
Here instead of extracting 0th element, I need to get sourceId based on sourceCode.
Sources is datasource name
So I tried below 3 different ways but error is thrown. Attached error.
1. def sourceId = context.expand( '${GetSources#Response#$[[?@.SourceCode=='${Sources#SourceCode}')].SourceId][\'SourceId\']}' )
2. def sourceId = context.expand( '${GetSources#Response#$[[?(@.SourceCode=='${Sources#SourceCode}')].SourceId]}')
3.def sourceId = context.expand( '${GetSources#Response#$[?(@.SourceCode=='${Sources#SourceCode}')].SourceId]}')
Please suggest the correct syntax .
Here is format of GET API Response
[
{
"SourceId": "bc3cef1e-a9f1-46df-a4f0-c1131357ea57",
"SourceCode": "ABC",
"CodeTier": "123",
"SourceDescription": "ABC Desc"
},
{
"SourceId": "b4035134-ca33-4b33-b3c7-06ea880f1f28",
"SourceCode": "DEF",
"CodeTier": "456",
"SourceDescription": "DEF Descr"
},
{
"SourceId": "9666bd19-1916-4052-9044-06b0e38e9175",
"SourceCode": "GHI",
"SourceDescription": "GHI Descr",
}
Hellotest wrote:
I tried first with out datasource as below but getting null pointer error as attached.
import static com.jayway.jsonpath.JsonPath.parse
def jsonString = context.expand( '${GetSources#Response}' )
def sourceId = new groovy.json.JsonSlurper().parseText(jsonString).result.find{it.SourceCode == 'ABC'}
log.info "source id: ${sourceId.SourceId}"You almost there, but trivial errors.
//Get the parsed json of GetSources test step response def json = new groovy.json.JsonSlurper().parseText(context('${GetSources#Response}')) //Closure to the the SourceId for a given SourceCode of the json def getSourceIdBySourceCode = { code -> json.find {it?.SourceCode == code}?.SourceId } //Check if the value is matching assert 'b4035134-ca33-4b33-b3c7-06ea880f1f28' == getSourceIdBySourceCode( 'DEF') assert 'bc3cef1e-a9f1-46df-a4f0-c1131357ea57' == getSourceIdBySourceCode( 'ABC')
You can test it online here