JsonPath
这里有个表格,说明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还有很多的语法(本地路径,操作符,和函数)没有列在这里。只要知道xpath和jsonpath脚本之中的不同点就行了。
- []在xpath表达式总是从前面的路径来操作数组,索引是从1开始。
- 使用JOSNPath的[]操作符操作一个对象或者数组,索引是从0开始。
- SONPath 例子
接下我们看jsonpath表示的例子。下面是一个简单的json数据结构代表一个书店(原始的xml文件是)
{ "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
}
}
}
| 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的书。 |
//* |
$..* |
所有元素。
|
浙公网安备 33010602011771号