python jsonpath 與 filter 提取資訊
阿新 • • 發佈:2021-08-30
1. filter
- filter() 函式用於過濾序列,過濾掉不符合條件的元素,返回由符合條件元素組成的新列表。
- 用法:filter(function, iterable)
infoList= { "Response": { "RequestId": "9d268c8f-26c4-d41d-cdcd-4f46c581100a", "Data": [ { "Id": 1000001, "ProjectCode": 110022, "ProjectName": "易方達", "Info":{ "card":13132123123, "bank_name":"中國銀行" } }, { "Id": 1000002, "ProjectId": 165519, "ProjectName": "中證800醫藥", "Info":{ "card":16455231231, "bank_name":"工商銀行" } }, { "Id": 1000003, "ProjectId": 516160, "ProjectName": "南方中證新能源", "Info":{ "card":16455231231, "bank_name":"農業銀行" } } ] } }
# 獲取匹配該資料的列表(若不匹配返回空列表) > [{'Id': 1000003, 'ProjectId': 516160, 'ProjectName': '南方中證新能源', 'Info': {'card': 16455231231, 'bank_name': '農業銀行'}}]
result = list(filter(lambda x: x["ProjectName"] == "南方中證新能源", infoList["Response"]["Data"]))
print(result)
2. jsonpath
- jsonpath() 是一種資訊抽取類庫,用來解析多層巢狀的json資料,存在返回列表,不存在返回False
- 用法:jsonpath(dict_data,'$..key_name'); 其中:“$”表示最外層的{},“..”表示模糊匹配,當傳入不存在的key_name時,程式會返回false
from jsonpath import jsonpath # 1. 獲取指定資料 > ['易方達', '中證800醫藥', '南方中證新能源'] print(jsonpath(infoList, "$..ProjectName")) # 2. 獲取第一條"bank_name" > ['易方達'] print(jsonpath(infoList, "$.Response.Data[0].ProjectName")) # 3. 不存在返回 False print(jsonpath(infoList, "$.Response.Total"))