eeadev
eeadev

Reputation: 3852

How to extract json var with Groovy and JMeter

Calling a REST API with JMeter 3.3, I have following JSON response:

{"map":{},"meta":{"code":"123"}}

How can I extract the value of code (123)?

So far I am using this:

with this 2 vars: code; meta and this json path expressions: $.code; $.meta

with this Groovy code:

String codeString =  vars.get("code");

String meta =  vars.get("meta");

log.info ("The code answer is " + codeString);  

if (codeString != "000"){
    AssertionResult.setFailureMessage("The code is: " + codeString + " - meta is: " + meta);

        AssertionResult.setFailure(true); 
}  

this is the assertion result instead:

Assertion error: false
Assertion failure: true
Assertion failure message: The code is: No_Default - meta is: {"code":"000"}

Upvotes: 2

Views: 3455

Answers (3)

Dmitri T
Dmitri T

Reputation: 168002

Given you use Groovy you don't need the JSON Path Extractor, you can validate your code like:

def code = com.jayway.jsonpath.JsonPath.read(prev.getResponseDataAsString(), '$..code').get(0).toString()
if (!code.equals('000')) {
     AssertionResult.setFailure(true)
     AssertionResult.setFailureMessage('The code is ' + code)
}

More information:

Upvotes: 3

Szymon Stepniak
Szymon Stepniak

Reputation: 42174

You can use JsonSlurper to extract the data you are interested in:

import groovy.json.JsonSlurper

String json = prev.getResponseDataAsString()

def root = new JsonSlurper().parseText(json)
def code = root.meta.code

Upvotes: 3

Ori Marko
Ori Marko

Reputation: 58774

You have a mistake in JSON path expression $.code for getting code, it's under second hierarchy and therefore you are missing ., use the following:

$..code

Upvotes: 2

Related Questions