JSONPath 笔记

继续 json 系列:

JSONPath 虽然简单,但偶尔用起来还要去求助搜索引擎,这里做下常用笔记。

在线验证: http://jsonpath.com/
Java包: https://github.com/json-path/JsonPath (GitHub上Star最多的)

操作符

符号 描述
$ 查询的根节点对象,用于表示一个json数据,可以是数组或对象
@ 过滤器断言(filter predicate)处理的当前节点对象,类似于java中的this字段
* 通配符,可以表示一个名字或数字
.. 可以理解为递归搜索,Deep scan. Available anywhere a name is required.
. 表示一个子节点
[‘’ (, ‘’)] 表示一个或多个子节点
[ (, )] 表示一个或多个数组下标
[start:end] 数组片段,区间为[start,end),不包含end
[?()] 过滤器表达式,表达式结果必须是boolean

函数

名称 描述 输出
min() 获取数值类型数组的最小值 Double
max() 获取数值类型数组的最大值 Double
avg() 获取数值类型数组的平均值 Double
stddev() 获取数值类型数组的标准差 Double
length() 获取数值类型数组的长度 Integer

过滤器

操作符 描述
== 等于符号,但数字1不等于字符1(note that 1 is not equal to ‘1’)
!= 不等于符号
< 小于符号
<= 小于等于符号
> 大于符号
>= 大于等于符号
=~ 判断是否符合正则表达式,例如[?(@.name =~ /foo.*?/i)]
in 所属符号,例如[?(@.size in [‘S’, ‘M’])]
nin 排除符号
size size of left (array or string) should match right
empty 判空符号

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
{
"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
}
},
"expensive": 10
}
JsonPath (click link to try) Result
$.store.book[*].author The authors of all books
$..author All authors
$.store.* All things, both books and bicycles
$.store..price The price of everything
$..book[2] The third book
$..book[-2] The second to last book
$..book[0,1] The first two books
$..book[:2] All books from index 0 (inclusive) until index 2 (exclusive)
$..book[1:2] All books from index 1 (inclusive) until index 2 (exclusive)
$..book[-2:] Last two books
$..book[2:] Book number two from tail
$..book[?(@.isbn)] All books with an ISBN number
$.store.book[?(@.price < 10)] All books in store cheaper than 10
$..book[?(@.price <= $[‘expensive’])] All books in store that are not “expensive”
$..book[?(@.author =~ /.*REES/i)] All books matching regex (ignore case)
$..* Give me every thing
$..book.length() The number of books