Search code examples
jsongroovyjmeter

Get the array object based on matching key in groovy


I have an HTTP request in the Jmeter, for which I am getting a JSON response consisting of an array.

Response:

{
    "Success": true,
    "RoomRecordsCount": 0,
    "RoomBookings": [],
    "DeskRecordsCount": 1,
    "DeskBookings": [
        {
            "BookingID": 569114,
            "BookingType": 2,
            "BookingStart": "11/07/2023 12:00 PM",
            "BookingEnd": "11/07/2023 23:59 PM",
            "TimeZoneOffSetInMins": 60,
            "TimeZone": "GMT Standard Time",
            "Status": 3,
            "AdditionalInformation": null,
            "FloorID": 0,
            "FloorName": "0",
            "CountryID": 9,
            "LocationID": 93,
            "LocationName": "AJ-LOC",
            "GroupID": 259,
            "GroupName": "AJ-GROUP",
            "DeskID": 29264,
            "DeskName": "Desk 2",
            "CanBeBooked": false,
            "DeskAttributes": null,
            "WSTypeId": 2,
            "WsTypeName": "MS Desk",
            "QRCodeEnabled": false,
            "bookMultipleDesk": true
        }
    ],
    "EditMiniSyncBooking": false,
    "Error": {
        "ErrorCode": 0,
        "ErrorDescription": ""
    }
}

This 'DeskBookings' can have multiple objects in its array. So I want only that object which matches with specific 'DeskID'

I wrote the groovy code in 'JSR223 PostProcessor'

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

def jsonSlurper = new JsonSlurper();
def response = jsonSlurper.parseText(prev.getResponseDataAsString());
def json = JsonOutput.toJson(response.findAll{ it.DeskBookings.DeskID == '29264' });

vars.put("bookingId", json.BookingID);

Error:

2023-07-11 00:07:57,966 ERROR o.a.j.e.JSR223PostProcessor: Problem in JSR223 script, JSR223 PostProcessor
javax.script.ScriptException: groovy.lang.MissingPropertyException: No such property: DeskBookings for class: java.util.LinkedHashMap$Entry

Solution

  • First of all you don't need to do any scripting, you can get the BookingID using JSON Extractor

    enter image description here

    If you still want to continue using Groovy consider following points:

    1. Your DeskID is an integer, you need to remove quotation marks from there
    2. There is no need to use JsonOutput
    3. vars.put() function expects 2 Strings and you're trying to put an integer there

    You need to amend your code as follows:

    def jsonSlurper = new JsonSlurper();
    
    def response = jsonSlurper.parse(prev.getResponseData());
    
    def deskBooking = response.DeskBookings.find {it.DeskID == 29264}
    
    vars.put("bookingId", deskBooking.BookingID as String);
    

    More information: