简体   繁体   中英

extracting single element from jsonpath array after query

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 on count such as count[0] doesn't work. But the expression $.results.payments[?(@.name == 'yesterday')].all.count when evaluated returns a Java list so to get the first count we can just get the first element from the list:

List<Integer> yesterdayCounts = ctx.read("$.results.payments[?(@.name == 'yesterday')].all.count");
int firstCount = yesterdayCounts.get(0);

assertThat(firstCount).isEqualTo(3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM