extracting single element from jsonpath array after query

邮差的信 提交于 2019-12-24 15:26:36

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/50768925/extracting-single-element-from-jsonpath-array-after-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!