jsonpath簡介
如果有一個多層嵌套的復雜字典,想要根據key批量提取value,還是比較繁瑣的。jsonPath模塊就能解決這個痛點,接下來我們來學習一下jsonpath模塊。
因為jsonpath是第三方模塊,想要使用需要安裝
pip install jsonpath
jsonpath使用方法
import jsonpath res=jsonpath.jsonpath(dict_data,'jsonpath語法規則字符串')
根據給定jsonpath語法規則,在dict_data中若能找到對應的數據,則以list類型返回數據,若找不到則返回false。
jsonpath語法規則
jsonpath使用示例
book_dict = { "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 } } from jsonpath import jsonpath # 獲取price的所有值 print(jsonpath(book_dict, '$..price')) # 獲取book下面所有元素 print(jsonpath(book_dict, "$.book.*")) # 獲取book下面所有price的值 print(jsonpath(book_dict, "$.book[*].price")) print(jsonpath(book_dict, "$.book..price")) # 獲取第1本書所有信息 print(jsonpath(book_dict, "$.book[0]")) # 獲取第2~3本書所有信息 print(jsonpath(book_dict, "$.book[1:3]")) # 獲取最后一本書 print(jsonpath(book_dict, "$.book[(@.length-1)]")) # 獲取包含了isbn的所有書 print(jsonpath(book_dict, "$.book[?(@.isbn)]")) # 獲取書的價格小於10的書 print(jsonpath(book_dict, "$.book[?(@.price<10)]"))
執行結果