基本语法
JSONPath语法元素和对应XPath元素的对比
XPath | JSONPath | Description |
---|---|---|
/ | $ | 根元素 |
. | @ | 当前元素 |
/ | . or [] | 子元素 |
.. | n/a | 父元素 |
// | .. | 递归下降,JSONPath是从E4X借鉴的。 |
* | * | 通配符,表示所有的元素 |
@ | n/a | 属性访问字符 |
[] | [] | 子元素操作符 |
[,] | 连接操作符在XPath 结果合并其它结点集合。JSONP允许name或者数组索引。 | |
n/a | [start: end: step] | 数组分割操作从ES4借鉴。 |
[] | ?() | 应用过滤表示式 |
n/a | () | 脚本表达式,使用在脚本引擎下面。 |
() | n/a | Xpath分组 |
示例对比
XPath | JSONPath | 结果 |
---|---|---|
/store/book/author | $.store.book[*].author | 书点所有书的作者 |
//author | $..author | 所有的作者 |
/store/* | $.store.* | store的所有元素。所有的bookst和bicycle |
/store//price | $.store..price | store里面所有东西的price |
//book[3] | $..book[2] | 第三个书 |
//book[last()] | $..book[(@.length-1)] | 最后一本书 |
//book[position() < 3] | $..book[0,1] $..book[:2] | 前面的两本书 |
//book[isbn] | $..book[?(@.isbn)] | 过滤出所有的包含isbn的书。 |
//book[price<10] | $..book[?(@.price<10)] | 过滤出价格低于10的书。 |
//* | $..* | 所有元素。 |
xpath索引下标是从1开始的
jsonpath索引下标是从0开始
data = {"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", "f": {"price": 22.99} } ], "bicycle": { "color": "red", "price": 19.95 } } } from jsonpath import jsonpath print(jsonpath(data, "$..price"))
结果输出如下: