Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a single value from a JSON object using JSONPath

Tags:

json

jsonpath

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

like image 710
Ilija Avatar asked May 12 '14 11:05

Ilija


People also ask

How get values from JsonPath?

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.

What is difference between JSON & JsonPath?

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.

How do I specify 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.

Can you use wildcards in JSON?

You can only perform wildcard matches against JSON properties with text (string) values.


1 Answers

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.

like image 159
Tim Avatar answered Sep 21 '22 01:09

Tim