I am trying to extract a value from a json string using json-path. I suspected that my question is related to Get specific object from JSONPath array result after predicate is applied but the link didn't provide me with the answer. My jsonfile looks like this:
{
"success": true,
"errorKey": null,
"results": {
"payments": [
{
"name": "current",
"all": {
"revenue": 390.32,
"count": 1
}
},
{
"name": "sameYesterday",
"all": {
"revenue": 613.24,
"count": 4
}
},
{
"name": "yesterday",
"all": {
"revenue": 613.24,
"count": 3
}
}
]
}
}
I want to get yesterday's payment count. Following query definitely works, but it relies on the position of elements within the json array, which can change:
ReadContext ctx = JsonPath.parse(content);
ctx.read("$.results.payments[2].all.count");
I was trying to work with name matching:
ctx.read("$.results.payments[?(@.name=='yesterday')].all.count[0]")
My problem is that this always returns an empty array. ctx.read("$.results.payments[?(@.name=='yesterday')].all.count" returns [3] (logically) and I assumed taking the first element from the result array would be sufficient, but my result array is always empty. What am I doing wrong?
count
property itself is not an array in your JSON so array notation oncount
such ascount[0]
doesn't work. But the expression$.results.payments[?(@.name == 'yesterday')].all.count
when evaluated returns a Java list so to get the firstcount
we can just get the first element from the list: