Python3下利用JsonPath解析資料
阿新 • • 發佈:2021-06-26
前言
常見Web介面返回資料的時候,大部分是以 JSON
的形式返回,如果返回資料量不大的話,我們可以直接通過 字典取值
或 正則取值
的方式來直接獲取。
但如果介面返回資料量比較大,或者巢狀的層級非常深,這種情況下使用
字典取值
就會變得有點困難;而正則取值
雖然是萬能的方法,但其只針對字串才能使用。
那麼在 Python 中,對於以上情況,有沒有更好更方便的方法呢?今天我們就來學習一款JSON解析神器:JsonPath,它是專門用來解析提取JSON資料用的。
本人環境:Python 3.7.0、jsonpath 0.82
JsonPath安裝
在 Python 中,為了使用JsonPath來解析資料,我們需要安裝第三方庫,命令如下:
pip3 install jsonpath
JsonPath語法示例
在 JsonPath 中使用 $
來表示根節點,或者說使用 $
來表示整個JSON資料。假如存在以下 data 資料:
{ "store": { "book": [ { "category": "新聞學", "author": "張三", "title": "圖書標題1", "price": 8.95 }, { "category": "金融學", "author": "李四", "title": "圖書標題2", "price": 12.00 }, { "category": "計算機", "author": "王五", "title": "圖書標題3", "isbn": "0-553-21311-3", "price": 9.99 }, { "category": "醫學", "author": "趙六", "title": "圖書標題4", "price": 22.99 } ], "phone": { "color": "red", "price": 1999.00, "author": "孫七" }, "author": "周八", "price": 1.00 }, "author": "吳九" }
以下是JsonPath的簡單語法示例:
JsonPath | 返回結果 |
---|---|
$.store.book[*].author | 所有book的author |
$.author | 僅子節點下的author |
$..author | 所有節點下的author |
$.store.* | store的所有元素,包括 book 和 phone |
$.store..price | store的所有price |
$..book[2] | book的第3個元素 |
$..book[(@.length - 2)] | book的倒數第2個元素 |
$..book[:2] | book的前面2個元素 |
$..book[-2:] | book的最後2個元素 |
$..book[0,3] | book的第1個元素、第4個元素 |
$..book[?(@.isbn)] | book中所有帶有 isbn 的元素 |
$.store.book[?(@.price < 10)] | book中所有price小於10的元素 |
$..* | 所有元素 |
注意:使用 JsonPath 時,索引是從 0 開始計算。
jsonpath使用
我們在Python中結合第三方庫 jsonpath
來處理JSON資料時,使用方式為:jsonpath.jsonpath(data, jsonpath表示式)
,如果成功從 data
中提取到資料,那麼會返回一個list列表,否則直接返回False。
import jsonpath
data = {
"store": {
"book": [
{
"category": "新聞學",
"author": "張三",
"title": "圖書標題1",
"price": 8.95
},
{
"category": "金融學",
"author": "李四",
"title": "圖書標題2",
"price": 12.00
},
{
"category": "計算機",
"author": "王五",
"title": "圖書標題3",
"isbn": "0-553-21311-3",
"price": 9.99
},
{
"category": "醫學",
"author": "趙六",
"title": "圖書標題4",
"price": 22.99
}
],
"phone": {
"color": "red",
"price": 1999.00,
"author": "孫七"
},
"author": "周八",
"price": 1.00
},
"expensive": 10,
"author": "吳九"
}
res1 = jsonpath.jsonpath(data, "$.store.book[*].author")
print("所有book的author:{}".format(res1))
res2 = jsonpath.jsonpath(data, "$.store..price")
print("store的所有price:{}".format(res2))
res3 = jsonpath.jsonpath(data, "$..book[0,3]")
print("book的第1個元素、第4個元素:{}".format(res3))
res4 = jsonpath.jsonpath(data, "$.store.book[?(@.price < 10)]")
print("book中所有price小於10的元素:{}".format(res4))