Search code examples
arraysobjectgatlingjsonpathscala-gatling

Gatling: How to extract one object from array?


I am new in Gatling and Scala. Sending Get Request the response body is Array and I need to extract only one object from Array and post it in Gatling. Can someone explain to me how to do it?

Here is my code example:

private val getUsers = exec(
      http("Get users")
        .get("/users")
        .check(status.is(200))
        .check(bodyString.saveAs("Users")))

The result that I get is:

[{"id":"1","hairColor":"BROWN","age":24,"language":"English","birthDate":"1995-02-10"},
{"id":"2","hairColor":"YELLOW","age":30,"language":"Australian","birthDate":"1889-10-05"},
{"id":"3","hairColor":"BLACK","age":15,"language":"American","birthDate":"..."},
{"id":"4","hairColor":"RED","age":50,"language":"Russian","birthDate":"..."}]

How to get whatever only one User from this array and post entire User object?


Solution

  • if you switch to a jsonPath check, you can get all the user objects into a Vector which has some nice support in the Gatling EL

    so instead of

    .check(bodyString.saveAs("Users"))
    

    you can use

    .check(jsonPath("$..[?(@.id)]").findAll.saveAs("Users")))
    

    then when you come to make your subsequent calls, you can do things like

    select the 1st user with

    .body(StringBody("${Body(1).jsonStringify()}"))
    

    select a random user with

    .body(StringBody("${Body.random().jsonStringify()}"))
    

    This approach will also allow you to use .forEach to interate over all the records