JsonPath 表达式可以用 类似 XPath 解析 XML 文档 的方式来解析 JSON 结构。
JsonPath expressions always refer to a JSON structure in the same way as XPath expression are used in combination with an XML document
依赖
JsonPath 已加入 Maven 中央仓库,添加依赖
1 | <dependency> |
表达式
Operator | 描述 | Description |
---|---|---|
$ |
根节点 | The root element to query. This starts all path expressions. |
@ |
当前节点 | The current node being processed by a filter predicate. |
* |
匹配任何一个数字和name | Wildcard. Available anywhere a name or numeric are required. |
.. |
深度扫描 | Deep scan. Available anywhere a name is required. |
.<name> |
选择name | Dot-notated child |
[] |
迭代器标示,如数组下标 | |
['<name>' (, '<name>')] |
一个或者多个name | Bracket-notated child or children |
[<number> (, <number>)] |
一个或者多个name | Array index or indexes |
[start:end] |
数组切片运算符 | Array slice operator |
[?(<expression>)] |
支持过滤操作 | Filter expression. Expression must evaluate to a boolean value. |
测试数据
1 | { |
测试
1 | import com.jayway.jsonpath.Criteria; |
函数
Functions can be invoked at the tail end of a path - the input to a function is the output of the path expression. The function output is dictated by the function itself.
函数 | 描述 | Description |
---|---|---|
min() |
最小值 | Provides the min value of an array of numbers |
max() |
最大值 | Provides the max value of an array of numbers |
avg() |
平均值 | Provides the average value of an array of numbers |
stddev() |
标准差=方差的算术平方根 | Provides the standard deviation value of an array of numbers |
length() |
长度 | Provides the length of an array |
示例
1 | {"numbers": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] } |
函数 | 描述 |
---|---|
$..book.length() |
书的个数 |
$.numbers.max() |
数组的最大值 |
$.numbers.avg() |
数组的平均值 |
过滤器操作
Operator | Description |
---|---|
== |
left is equal to right (note that 1 is not equal to ‘1’) |
!= |
left is not equal to right |
< |
left is less than right |
<= |
left is less or equal to right |
> |
left is greater than right |
>= |
left is greater than or equal to right |
=~ |
left matches regular expression [?(@.name =~ /foo.*?/i)] |
in |
left exists in right [?(@.size in ['S', 'M'])] |
nin |
left does not exists in right |
size |
size of left (array or string) should match right |
empty |
left (array or string) should be empty |
示例
[?(@.price < 10 && @.category == 'fiction')]
[?(@.category == 'reference' || @.price > 10)]