xPath是一种XML遍历的语法,可以从XML文档中提取特定的元素、属性、数据。
jsonPath是类似xPath的查询语法,可以从Json文档中提取特定的元素、属性、数据。
-
JsonPath与XPath语法对比:
下面以一个json文本为案例,展示一下jsonPath和xPath的用法:
{ "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
}
}
}
例如
- 查找店铺store里所有书本的作者名字
- jsonPath使用: $.store.book[*].author
- 如果是同种结构的xml文档,xPath使用: /store/book/author
结果是:
["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]
- 查找书本标题为“Sword of Honour”的作者名字
- jsonPath使用:$..book[?(@.title=='Sword of Honour')].author
- xPath使用: //book[@title='Sword of Honour']/author
结果是:
["Evelyn Waugh"]
更多查找案例如下: