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"
).
I was using the Java implementation of JSONPath and got to the very same issue. What worked for me was to add '[0]' to the json path string. So in your case:
$.single.name[0]
but I always get an array:
That is meant to happen. As you can read in this documentation, under 'Result' (almost at the bottom):
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.
I think, it depends of language implementation.
For example in nodejs there is a npm module : https://www.npmjs.com/package/jsonpath
Which have a method called value, which does exactly what we need
jp.value(obj, pathExpression[, newValue])
I tried it and worked!
I know this is an old question , but the following worked for me when writing unit test for a spring boot application. Hope this helps someone in a similar situation.
As Tim Castelijns mentioned , the result is always an array.
Sample Json
and the unit test part