Get last element of JSON tab of objects response

I have a project where I need to get the last object of a JSON list that is returned in JSON but I can’t get any idea of how to from a .check
My builder:

    ChainBuilder getAllOrders = exec(http("Orders: /api/orders")
            .get("/api/orders")
            .header("Authorization", "Bearer ${BearerToken}")
            .check(status().is(200))
            .check(jsonPath("$..id").saveAs("OrderIds")));

The response of the get is

"[
  {
    "id": 3,
    "order_number": "{ord_nb}",
    "date": "{date}",
    "amount": "{amt}"
  },
  {
    "id": 4,
    "order_number": "{ord_nb}",
    "date": "{date}",
    "amount": "{amt}"
  }
]"

But actually if I use that check I get the id = 3 but I need to get id = 4
I tried to check if there was a solution something in the documentation but I didn’t found any method, path that could’ve helped (like: “$.[-1:].id”) or even using length (and I checked the similar blogs but didn’t found any answer)

If any information is missing I could provide what’s needed.
Thanks in advance

Use jmesPath instead jsonPath.
For you case should help:

jmesPath("[-1].id")

or if you want max value - sometimes values in array can be mixed so you want max value:

jmesPath("max([].id)")
1 Like

After some tests it seems like this “jsonPath(”$[-1].id")“/“jsonPath(”$[-1:].id”)" works too (without the first dot)
but your jmesPath works too so I’ll put your answer as solution.
Thanks a lot!

Generally speaking, JsonPath is mess because of the lack of a proper spec. As a result, results and syntax can be different in different implementation (eg online editor in JS vs Gatling).
I recommend you use JMesPath whenever possible.

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.