更新時間:2021-05-27 來源:黑馬程序員 瀏覽量:
JSONPath是一種信息抽取類庫,是從JSON文檔中抽取指定信息的工具,提供多種語言實現(xiàn)版本,包括Javascript、Python、PHP和Java。
JSONPath的安裝方法如下:
pip install jsonpathJSONPath語法和XPATH語法對比 JSON結(jié)構(gòu)清晰,可讀性高,復(fù)雜度低,非常容易匹配。JSONPath的語法與Xpath類似,如下表所示為JSONPath與XPath語法對比。
XPATH |
JSONPATH |
描述 |
/ |
$ |
根節(jié)點 |
. |
@ |
現(xiàn)行節(jié)點 |
/ |
.or[] |
取子節(jié)點 |
.. |
n/a |
取父節(jié)點,JSONPath未支持 |
// |
.. |
不管位置,選擇所有符合條件的節(jié)點 |
* |
* |
匹配所有元素節(jié)點 |
@ |
n/a |
根據(jù)屬性訪問,JSON不支持,因為JSON是個key-value遞歸結(jié)構(gòu),不需要屬性訪問 |
[] |
[] |
迭代器標示(可以在里面做簡單的迭代操作,如數(shù)組下標、根據(jù)內(nèi)容選值等) |
| |
[,] |
支持迭代器中做多選 |
[] |
?() |
支持過濾操作 |
n/a |
() |
分組,JSONPath不支持 |
下面使用一個JSON文檔演示JSONPath的具體使用。JSON 文檔的內(nèi)容如下:
{ "store": { "book":[ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "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 } } }
假設(shè)變量bookJson中已經(jīng)包含了這段JSON字符串,可通過以下代碼反序列化得到JSON對象:
books=json.loads(bookJson)
checkurl = "$.store.bicycel.color" print(jsonpath.jsonpath(books, checkurl)) # 輸出:['red']
(2)輸出book節(jié)點中包含的所有對象:
checkurl = "$.store.book[*]" object_list=jsonpath.jsonpath(books, checkurl) print(object_list)
(3)輸出book節(jié)點的第一個對象:
checkurl = "$.store.book[0]" obj = jsonpath.jsonpath(books, checkurl) print(obj) # 輸出: ['category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 8.95}]
(4)輸出book節(jié)點中所有對象對應(yīng)的屬性title值:
checkurl = "$.store.book[*].title" titles = jsonpath.jsonpath(books, checkurl) print(titles) # 輸出: ['Sayings of the Century', 'The Lord of the Rings']
(5)輸出book節(jié)點中category為fiction的所有對象:
checkurl = "$.store.book[?(@.category=='fiction')]” books=jsonpath.jsonpath(books, checkurl) print(books) # 輸出:[{'category': 'fiction', 'author': 'J. R. R. Tolkien', 'title': 'The Lordof the Rings', 'isbn': '0-395-19395-8', 'price': 22.99}]
(6)輸出book節(jié)點中所有價格小于10的對象:
checkurl="$.store.book[?(@.price<10)]" books = jsonpath.jsonpath(books, checkurl) print(books) # 輸出: [{'category': 'reference', 'author': 'Nigel Rees', 'title':'Sayings of the Century', 'price': 8.95}]
(7)輸出book節(jié)點中所有含有isb的對象:
checkurl = "$.store.book[?(@.isb)]" books = jsonpath.jsonpath(books,checkurl) print(books) # 輸出: [{'category': 'fiction', 'author': 'J. R. R. Tolkien', 'title': 'The Lord of the Rings', 'isbn': '0-395-19395-8', 'price': 22.99}]
猜你喜歡:
Python os.listdir()函數(shù)用法介紹