I have the following JSON and I need to get the plain name
value using JSONPath:
{ "single" : { "id" : 1, "name" : "Item name" } }
Expression that I used is $.single.name
but I always get an array:
[ "Item name" ]
instead of a string value ("Item name"
).
We can use JsonPath in Rest Assured to extract value. This is done with the help of the jsonPath method (which is a part of the JsonPath class). After that, we need to use the get method and pass the key that we want to obtain from the JSON Response.
JSONPath creates a uniform standard and syntax to define different parts of a JSON document. JSONPath defines expressions to traverse through a JSON document to reach to a subset of the JSON. This topic is best understood by seeing it in action. We have created a web page which can help you evaluate a JSONPath.
You use a JSONPath expression to traverse the path to an element in the JSON structure. You start at the root node or element, represented by $, and reach the required element in the JSON structure to extract data from it. You can use either the dot-notation or the bracket-notation to form the expressions.
You can only perform wildcard matches against JSON properties with text (string) values.
but I always get an array:
That is meant to happen. As you can read in this documentation, under 'Result' (almost at the bottom):
Please note, that the return value of jsonPath is an array, which is also a valid JSON structure. So you might want to apply jsonPath to the resulting structure again or use one of your favorite array methods as sort with it.
So basically it will always return an array. If you need the data as an other type, e.g. a String in this case, you will have to do the conversion yourself I'm afraid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With