Reputation: 6208
I have strange case for jmeter. Imagine that we have an json array with elements like this:
{
"id" : 123456,
"name": "TEST"
}
So I want to get random element from array that has id
. For this case I use Json Path PostProcessor
with expression like this $.elements[?(@.id)]
But for some reasons I need an index of this element. So I can create BeanShellPostProcessor
generate random index and then use same Json Path PostProcessor
with expression like this $.elements[${PARAM_ElementIndex}]
.
But in some cases this array can be empty and Json Path PostProcessor
wil fail with exception like this:
jmeter.extractor.json.jsonpath.JSONPostProcessor: Error processing JSON content in PARAM_ResumeId, message:No results for path: $['elements'][0]['id']
So may be someone can suggest any solution
Upvotes: 1
Views: 2672
Reputation: 168132
I would recommend use Groovy instead of Beanshell as:
So given you have JSON Response like:
{
"elements": [
{
"id": 123456,
"name": "TEST"
},
{
"id": 7890,
"name": "TEST2"
}
]
}
You can extract random ID along with its index using the following example Groovy code in the JSR223 PostProcessor:
import groovy.json.JsonSlurper
import java.util.concurrent.ThreadLocalRandom
String response = prev.getResponseDataAsString()
def jsonSlurper = new JsonSlurper()
def json = jsonSlurper.parseText(response)
int size = json.elements.size
if (size > 0){
def randomIndex = ThreadLocalRandom.current().nextInt(size)
def value = json.elements.get(randomIndex).id
log.info('Index: ' + randomIndex)
log.info('Value: ' + value)
}
Demo:
References:
Upvotes: 2