在JSONPath中选择第一个筛选结果

时间:2015-05-19 09:45:44

标签: json jsonpath

我一直在尝试使用JSONPath过滤我的JSON中的特定元素,然后只选择返回的结果数组中的第一项。

我的baisc JSONPath看起来像这样:

$.store.book[?(@.category==fiction)].price

我想像这样添加这个[0]过滤器:

$.store.book[?(@.category==fiction)][0].price

但它没有返回结果,或者我将[0]放在最后一个"价格"之后我收到这个错误:

  

过滤:[0] ['价格']只能应用于数组

我一直在搜索,并且无法找到正确的语法来在应用过滤器后拉出数组中的第一个元素,就像在xpath中一样。

这是我正在研究的基础JSON:

{ "store": {
    "book": [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

2 个答案:

答案 0 :(得分:1)

目前唯一的解决方案是:

List<Double> prices = JsonPath
   .parse(json)
   .read("$.store.book[?(@.category == 'fiction')].price");

Double firstPrice = prices.isEmpty() ? null : prices.get(0);

答案 1 :(得分:1)

当你想用jsonpath和spring mvc时,我最终得到了

.andExpect(jsonPath("$[?(@.name.value == 'Item')].depth", is(Collections.singletonList(2))))

而不是

.andExpect(jsonPath("$[?(@.name.value == 'Item')][0].depth", is(2)))

以前用于旧版本(0.9.1)的方式