Search code examples
groovyjmeterperformance-testing

How to use object.find on nested Value


i have an object in grovvy with a list of key:value pairs. I'm using this code to extract only the matrix value for this Object.

Object :

[{"id":null,"dimension":"f7f04751-5ac9-4867-a742-6f69a53d99d3","matrix_value":"ac726cd4-0aaf-4b4b-91c1-bceda8dded04","name":"Linear","include":false,"children":[{"id":null,"dimension":"f7f04751-5ac9-4867-a742-6f69a53d99d3","matrix_value":"efc05bdb-ebc8-4167-85fb-9e5a63a1200b","name":"Little Linear","include":false,"children":[]}]},{"id":null,"dimension":"f7f04751-5ac9-4867-a742-6f69a53d99d3","matrix_value":"a2b932d3-14f0-480f-8eeb-d1fc00a1c7ab","name":"Not Linear","include":false,"children":[]}]

I know that with it.name i search only at the top level values of the object. How can i modify this code to check if the field children is not null and in that case apply the find also to the child element and extract the matrix_valiue? Thank you.

import groovy.json.JsonSlurper;


def Dimensions = vars.getObject("Dimensions")



String[] DimensionKeyset = vars.getObject("DimensionKeySet");
String Dimension_name = DimensionKeyset[Integer.parseInt(vars.get("ContoDimensions"))]
String[] Values = Dimensions.get(Dimension_name)
def Body = vars.get("Body_Get")
def jsonSlurper = new JsonSlurper();
def list = jsonSlurper.parseText(Body);
def rc_dimension_values = []
log.info("La lista è: "+ list.toString())

log.info("La vera lista è: "+ list.getClass())


for(v : Values) {
    
    rc_dimension_values += list.find { it.name.trim() == v.trim() }.matrix_value
     log.info("L'oggetto è:" + list.find { it.name.trim() == v.trim() } )
    log.info("Check For Values: " + v)

    
    
}

def builder = new groovy.json.JsonBuilder(rc_dimension_values)

vars.put("rc_dimension_values", builder.toString());


Solution

  • If you just want to get all matrix_value wherever they are the easiest would be switching to JSON Extractor. If you use deep scan operator like:

    $..matrix_value
    

    it will store all the values to the JMeter Variables:

    enter image description here


    If you want to stay with Groovy you can use the following code snippet which uses the same JsonPath library which is under the hood of the JSON Extractor:

    vars.put('rc_dimension_values',new groovy.json.JsonBuilder(com.jayway.jsonpath.JsonPath.read(prev.getResponseDataAsString(),'$..matrix_value')).toPrettyString())
    

    it will generate a JSON Array from the found matrix_value attributes and store it into rc_dimension_values variable:

    enter image description here