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

有帮助吗?

解决方案

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.

其他提示

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]

It depends of the library implementations in which some of them are rigid and others offer an option to make the developer smile.

Nodejs

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

Returns the value of the first element matching pathExpression. If newValue is provided, sets the value of the first matching element and returns the new value.

Java

String json = "...";
Object document = ...parse(json);
String author0 = JsonPath.read(document, "$.store.book[0].author");

As you can see author0 is a string, not an array

Source: https://github.com/json-path/JsonPath

In case you got this error

"Unable to get a scalar value for expression $.yourfield"

You have just to configure the EvaluateJsonPath processor by changing the return type property value to 'json' instead of 'auto-detect'

enter image description here

In an Azure Bicep template, value worked for me, in extracting a single parameter from a jsonc parameter file: $.parameters.aksAgentPoolIdentityPrincipalId.value

One could fathom a guess that in my case this is used as the implementation:
https://github.com/json-path/JsonPath

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top