更新時(shí)間:2021年05月27日14時(shí)36分 來源:傳智教育 瀏覽次數(shù):
JSONPath是一種信息抽取類庫,是從JSON文檔中抽取指定信息的工具,提供多種語言實(shí)現(xiàn)版本,包括Javascript、Python、PHP和Java。
JSONPath的安裝方法如下:
pip install jsonpathJSONPath語法和XPATH語法對(duì)比 JSON結(jié)構(gòu)清晰,可讀性高,復(fù)雜度低,非常容易匹配。JSONPath的語法與Xpath類似,如下表所示為JSONPath與XPath語法對(duì)比。
XPATH | JSONPATH | 描述 |
/ | $ | 根節(jié)點(diǎn) |
. | @ | 現(xiàn)行節(jié)點(diǎn) |
/ | .or[] | 取子節(jié)點(diǎn) |
.. | n/a | 取父節(jié)點(diǎn),JSONPath未支持 |
// | .. | 不管位置,選擇所有符合條件的節(jié)點(diǎn) |
* | * | 匹配所有元素節(jié)點(diǎn) |
@ | n/a | 根據(jù)屬性訪問,JSON不支持,因?yàn)镴SON是個(gè)key-value遞歸結(jié)構(gòu),不需要屬性訪問 |
[] | [] | 迭代器標(biāo)示(可以在里面做簡單的迭代操作,如數(shù)組下標(biāo)、根據(jù)內(nèi)容選值等) |
| | [,] | 支持迭代器中做多選 |
[] | ?() | 支持過濾操作 |
n/a | () | 分組,JSONPath不支持 |
下面使用一個(gè)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對(duì)象:
books=json.loads(bookJson)
checkurl = "$.store.bicycel.color" print(jsonpath.jsonpath(books, checkurl)) # 輸出:['red']
(2)輸出book節(jié)點(diǎn)中包含的所有對(duì)象:
checkurl = "$.store.book[*]" object_list=jsonpath.jsonpath(books, checkurl) print(object_list)
(3)輸出book節(jié)點(diǎn)的第一個(gè)對(duì)象:
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é)點(diǎn)中所有對(duì)象對(duì)應(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é)點(diǎn)中category為fiction的所有對(duì)象:
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é)點(diǎn)中所有價(jià)格小于10的對(duì)象:
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é)點(diǎn)中所有含有isb的對(duì)象:
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}]
猜你喜歡:
北京校區(qū)