JSONPath 可以方便对 JSON 数据结构进行内容提取。JSONPath 之于 JSON,就如 XPath 之于 XML。
官方 API 文档:https://github.com/json-path/JsonPath
如果你对 JSON Path 不熟悉,推荐使用这个免费的 AI 工具来生成:https://app.anakin.ai/apps/21854
JSONPath | 描述 |
---|---|
$ | 根对象或元素。 |
@ | 当前对象或元素。 |
. or [] | 子元素操作符。 比如:$.store.book[0].title 或 $['store']['book'][0]['title'] |
.. | 递归匹配所有子元素。 |
* | 通配符. 匹配所有对象或元素。 |
[] | 下标运算符,JsonPath索引从0开始。 |
[,] | 连接运算符,将多个结果拼成数组返回,JSONPath允许使用别名。 |
[start:end:step] | 数组切片运算符。 |
?() | 过滤器(脚本)表达式。 |
(<expr>) | 脚本表达式。 |
要点:
1. 根对象使用 $ 来表示,而无需区分是对象还是数组。
2. 表达式可以使用 . ,也可以使用 [] 。如:
$.store.book[0].title 或 $['store']['book'][0]['title']。
3. 表达式(<expr>)可用作显式名称或索引的替代,如:
$.store.book[(@.length-1)].title 表示获取最后一个 book 的 title。
4. 使用符号@表示当前对象。过滤器表达式通过语法支持,?(<boolean expr>)如:
$.store.book[?(@.price < 10)].title 表示获取价格小于 10 的所有 book 的 title。
函数 | 描述 | 输出类型 |
---|---|---|
min() | ||
max() | ||
avg() | ||
stddev() | ||
length() | ||
sum() |
例如有下面的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 } } } |
JsonPath | Result |
---|---|
$.store.book[*].author | 所有 book 的 author 节点 |
$..author | 所有 author 节点 |
$.store.* | store 下的所有节点,book 数组和 bicycle 节点 |
$.store..price | store 下的所有 price 节点 |
$..book[2] | 匹配第 3 个 book 节点 |
$..book[(@.length-1)] ,或 $..book[-1:] | 匹配倒数第 1 个 book 节点 |
$..book[0,1] ,或 $..book[:2] | 匹配前两个 book 节点 |
$..book[?(@.isbn)] | 过滤含 isbn 字段的节点 |
$..book[?(@.price<10)] | 过滤price<10 的节点 |
$..* | 递归匹配所有子节点 |
$.store.book.length() | book 总数 |