Swapnil Swapnil - 1 year ago 234
JSON Question

jsonpath find string value in the jsonarray independent of array index

I have a Gatling JSON objects of array. The object contains error messages e.g.

"error": [
"errorCode": "111",
"errorMessage": "very dynamic error :- at [Source: java.io.PushbackInputStream@5d0edb12; line: 6, column: 6]; nested exception is com.fasterxml.jackson.core.JsonParseException: "
"errorCode": null,
"errorMessage": "Fixed Error Message"
"errorCode": "112",
"errorMessage": "Again some error message"

and I'm checking jsonpath as

($.error[1].errorMessage).is("Fixed Error Message")

But, different API's have different error object and fixed errorMessage can be placed in the array at any index location.

How can I dynamically check whether that fixed errorMessage present in the jsonArray without worrying about arrayIndex ?

Can I make a query which independently match the string with array element without mentioning the array index, something like below?
($.error[*].errorMessage).is("Fixed Error Message")

Answer Source

You can filter the array with the following:

JsonPath.query("$.error[?(@.errorMessage=='Fixed Error Message')]", json)


This would be preferred to check if the message was actually found:

jsonPath("$.error[?(@.errorMessage=='Fixed Error Message')]").exists

If you want to do the .is() check you can try the following (not very nice):

jsonPath("$.error[?(@.errorMessage=='Fixed Error Message')].errorMessage").is("Fixed Error Message")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download