安装jsonpath:
pip install jsonpath
JsonPath与XPath语法对比:
Json结构清晰,可读性高,复杂度低,非常容易匹配,下表中对应了XPath的用法。
import jsonpath
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
}
},
"expensive": 10
}
# The authors of all books:获取json中store下book下的所有author值
jsonpath.jsonpath(json, "$.store.book[*].author")
# All authors:获取所有json中所有author的值
jsonpath.jsonpath(json, "$..author")
# All things, both books and bicycles # authors3返回的是net.minidev.json.JSONArray:获取json中store下的所有value值,不包含key,如key有两个,book和bicycle
jsonpath.jsonpath(json, "$.store.*")
# The price of everything:获取json中store下所有price的值
jsonpath.jsonpath(json, "$.store..price")
# The third book:获取json中book数组的第3个值
jsonpath.jsonpath(json, "$..book[2]")
# The first two books:获取json中book数组的第1和第2两个个值
jsonpath.jsonpath(json, "$..book[0,1]")
# All books from index0(inclusive) until index2(exclusive):获取json中book数组的前两个区间值
jsonpath.jsonpath(json, "$..book[:2]")
# All books from index1(inclusive) until index2(exclusive):获取json中book数组的第2个值
jsonpath.jsonpath(json, "$..book[1:2]")
# Last two books:获取json中book数组的最后两个值
jsonpath.jsonpath(json, "$..book[-2:]")
# Book number two from tail:获取json中book数组的第3个到最后一个的区间值
jsonpath.jsonpath(json, "$..book[2:]")
# All books with an ISBN number:获取json中book数组中包含isbn的所有值
jsonpath.jsonpath(json, "$..book[?(@.isbn)]")
# All books in store cheaper than 10:获取json中book数组中price < 10 的所有值
jsonpath.jsonpath(json, "$.store.book[?(@.price < 10)]")
# All books in store that are not "expensive":获取json中book数组中price <= expensive的所有值
jsonpath.jsonpath(json, "$..book[?(@.price <= $['expensive'])]")
# All books in store that price is 22.99:获取json中book数组中price == 22.99的所有值
jsonpath.jsonpath(json, "$..book[?(@.price == 22.99)]")
# Get title that price is 22.99:获取json中book数组中price == 22.99的节点的“title”值
jsonpath.jsonpath(json, "$..book[?(@.price == 22.99)].title")
# 获取json中book数组中price小于10的title
jsonpath.jsonpath(json, "$.store.book[?(@.price < 10)].title")
# All books matching regex(ignore case):获取json中book数组中的作者以REES结尾的所有值(REES不区分大小写)
jsonpath.jsonpath(json, "$..book[?(@.author =~ /.*REES/i)]")
# Give me every thing:逐层列出json中的所有值,层级由外到内
jsonpath.jsonpath(json, "$..*")
# The number of books:获取json中book数组的长度
jsonpath.jsonpath(json, "$..book.length()")
# 获取json中book数组倒数第二个对象的title
jsonpath.jsonpath(json, "$.store.book[(@.length-1)].title")