Getting a single value from a JSON object using JSONPath

Ilija picture Ilija · May 12, 2014 · Viewed 59.5k times · Source

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

Answer

Tim picture Tim · May 13, 2014

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.