JsonPath為Json文檔提供了解析能力,通過使用JsonPath,你可以方便的查找節點、獲取想要的數據,JsonPath是Json版的XPath,正如XPath之於XML文檔一樣。
JsonPath語法
ps:JsonPath語法現在並沒有形成統一的標准。
JsonPath語法要點:
$ 表示文檔的根元素
@ 表示文檔的當前元素
.node_name 或 ['node_name'] 匹配下級節點
[index] 檢索數組中的元素
[start:end:step] 支持數組切片語法
* 作為通配符,匹配所有成員
.. 子遞歸通配符,匹配成員的所有子元素
(<expr>) 使用表達式
?(<boolean expr>)進行數據篩選
注意:
-
JsonPath的索引從0開始計數
-
JsonPath中字符串使用單引號表示,例如:$.store.book[?(@.category=='reference')]中的'reference'
JsonPath示例
{
"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
}
}
}
python中使用jsonpath
import jsonpath
r={
"errcode": 0,
"errmsg": "ok",
"taglist": [
{
"tagid": 2,
"tagname": "修改后的標簽名"
},
{
"tagid": 3,
"tagname": "test004"
},
{
"tagid": 4,
"tagname": "test005"
},
{
"tagid": 5,
"tagname": "test002"
}
]
}
# 從jsno數據中取值,判斷數據是否在json中
def test_json():
res=jsonpath.jsonpath(r,'$..tagname')
print(res) # 返回一個數組
print(len(res))
assert 'test002' in res
結果:
['修改后的標簽名', 'test004', 'test005', 'test002']
4
參考:
https://www.cnblogs.com/youring2/p/10942728.html
https://blog.csdn.net/xc_zhou/article/details/89500219
https://www.cnblogs.com/denise1108/p/10265911.html