Python中使用JsonPath

Python中使用JsonPath

JsonPath是解析Json字符串用的,類似於Xpath,使用JsonPath可以根據語法提取Json串中的關鍵信息和相關鍵值,無論嵌套了多少層,都能提取出來,省去了先反序列化成對象再取值的麻煩,堪稱一項偉大的發明。

1. JsonPath語法

1.1 常用語法
  • $ 表示文檔的根元素
  • @ 表示文檔的當前元素
  • .node_name 或 [‘node_name’] 匹配下級節點
  • [index] 檢索數組中的元素
  • [start : end : step] 支持數組切片語法
  • * 作爲通配符,匹配所有成員
  • … 子遞歸通配符,匹配成員的所有子元素
  • () 使用表達式
  • ?()進行數據篩選
1.2 與xpath對比
XPath JsonPath 說明
/ $ 文檔根元素
. @ 當前元素
/ .或[] 匹配下級元素
N/A 匹配上級元素,JsonPath不支持此操作符
// 遞歸匹配所有子元素
* * 通配符,匹配下級元素
@ N/A 匹配屬性,JsonPath不支持此操作符
[] [] 下標運算符,根據索引獲取元素,XPath索引從1開始,JsonPath索引從0開始
| [,] 連接操作符,將多個結果拼接成數組返回,可以使用索引或別名
N/A [start: end:step] 數據切片操作,XPath不支持
[] ?() 過濾表達式
N/A () 腳本表達式,使用底層腳本引擎,XPath不支持
() N/A 分組,JsonPath不支持

注意:

  • JsonPath的索引從0開始計數
  • JsonPath中字符串使用單引號表示,例如:$.store.book[?(@.category==‘reference’)]中的’reference’

2. 官方使用實例

下面是示範用的Json字符串,使用的官方文檔中的例子,https://goessner.net/articles/JsonPath/

{
	"store": {
		"book": [{
				"category": "reference",
				"author": "Nigel Rees",
				"title": "Sayings of the Century",
				"price": 8.2
			}, {
				"category": "fiction",
				"author": "Evelyn Waugh",
				"title": "Sword of Honour",
				"price": 2.99
			}, {
				"category": "fiction",
				"author": "Herman Melville",
				"title": "Moby Dick",
				"isbn": "0-553-21311-3",
				"price": 8.09
			}, {
				"category": "fiction",
				"author": "J. R. R. Tolkien",
				"title": "The Lord of the Rings",
				"isbn": "0-395-19395-8",
				"price": 2.99
			}
		],
		"bicycle": {
			"color": "red",
			"price": 19.95
		}
	}
}

使用JsonPath解析實例

XPath JsonPath Result
/store/book/author $.store.book[*].author 所有book的author節點
//author $…author 所有author節點
/store/* $.store.* store下的所有節點,book數組和bicycle節點
/store//price $.store…price store下的所有price節點
//book[3] $…book[2] 匹配第3個book節點
//book[last()] $…book[(@.length-1)],或 $…book[-1:] 匹配倒數第1個book節點
//book[position() < 3] $…book[0,1],或 $…book[:2] 匹配前兩個book節點
//book[isbn] $…book[?(@.isbn)] 過濾含isbn字段的節點
//book[price<10] $…book[?(@.price<10)] 過濾price<10的節點
//* $…* 遞歸匹配所有子節點

3. python使用實例

在python使用及其簡單,只需要用pip安裝一下:pip install jsonpath,之後導入這個包:import jsonpath,就可以使用了。這裏引用一位大哥寫的例子來說明:

d={
	"error_code": 0,
		"stu_info": [
				{
						"id": 2059,
						"name": "小白",
						"sex": "男",
						"age": 28,
						"addr": "河南省濟源市北海大道32號",
						"grade": "天蠍座",
						"phone": "18378309272",
						"gold": 10896,
						"info":{
							"card":434345432,
							"bank_name":'中國銀行'
						}

				},
				{
						"id": 2067,
						"name": "小黑",
						"sex": "男",
						"age": 28,
						"addr": "河南省濟源市北海大道32號",
						"grade": "天蠍座",
						"phone": "12345678915",
						"gold": 100
				}
		]
}
#取某個學生姓名的原始方法:通過查找字典中的key以及list方法中的下標索引
res= d["stu_info"][1]['name'] print(res) #輸出結果是:小黑

import jsonpath

#嵌套n層也能取到所有學生姓名信息,$表示最外層的{},..表示模糊匹配
res1=jsonpath.jsonpath(d,'$..name') 
print(res1) #輸出結果是list:['小白', '小黑']

res2= jsonpath.jsonpath(d,'$..bank_name')
print(res2) #輸出結果是list:['中國銀行']

res3=jsonpath.jsonpath(d,'$..name123') #當傳入不存在的key(name)時,返回False
print(res3) #輸出結果是:False

4. 官方文檔

https://goessner.net/articles/JsonPath/

5. Newtonsoft.Json參考

此外.net中的Newtonsoft.Json也支持Jsonpath,詳見官方文檔:https://www.newtonsoft.com/json/help/html/SelectToken.htm

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章