Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")

like image 231
Swapnil Kotwal Avatar asked Sep 20 '16 02:09

Swapnil Kotwal


People also ask

What is the output of JSONPath method?

3.3. JsonPath also has functions that we can use at the end of a path to synthesize that path's output expressions: min(), max(), avg(), stddev() and length(). Finally, we have filters. These are boolean expressions to restrict returned lists of nodes to only those that calling methods need.

What does JSONPath return?

JSONPath is a query language for JSON, similar to XPath for XML. It allows you to select and extract data from a JSON document. You use a JSONPath expression to traverse the path to an element in the JSON structure.

What is Jayway JSONPath?

Jayway JsonPath is a Java port of Stefan Goessner JsonPath implementation.

What is array slice operator in JSONPath?

: operator is the array slice operator, so you can slice collections using the syntax [start:end:step] to return a subcollection of a collection. ( ) operator lets you pass a script expression in the underlying implementation's script language. It's not supported by every implementation of JSONPath, however.


1 Answers

You can filter the array with the following:

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

EDIT 1:

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")
like image 52
Piotr Reszke Avatar answered Oct 05 '22 13:10

Piotr Reszke