JsonPath 是一种信息抽取类库,是从JSON文档中抽取指定信息的工具,提供多种语言实现版本,包括:Javascript, Python, PHP 和 Java
python如何使用JsonPath?
在python中,也有相同功能的第三方庫:jsonpath
jsonpath安裝:
pip install jsonpath
用法:
jsonpath.jsonpath(obj,jsonpath语句)
例如:
jsonpath.jsonpath(dic_j,”$..id“)
我们来看一个例子:
import jsonpath json_data = {"result": "1", "item": [ {"id": None, "goodId": 22481,"sequence": 29, "goodStatus": "1", "shopStatus": "7", "shopId": 280, "mallHomeTypeId": 38, "price": 16.8, "sales": 23870, "advertId": 37955}, {"id": None, "goodId": 31100, "sequence": 28, "goodStatus": "1", "shopStatus": "7", "shopId": 377, "mallHomeTypeId": 38, "price": 15.8, "sales": 19276, "advertId": 37957}, {"id": None, "goodId": 40027, "sequence": 27, "goodStatus": "1", "shopStatus": "7", "shopId": 221, "mallHomeTypeId": 38, "price": 13.66, "sales": 27822, "advertId": 37959}, {"id": None, "goodId": 2138, "sequence": 26, "goodStatus": "1", "shopStatus": "7", "shopId": 82, "mallHomeTypeId": 38, "price": 12.9, "sales": 3515, "advertId": 37960}, {"id": None, "goodId": 41843,"sequence": 25, "goodStatus": "1", "shopStatus": "7", "shopId": 50, "mallHomeTypeId": 38, "price": 12.9, "sales": 56093, "advertId": 37963}, ] } d_price = jsonpath.jsonpath(json_data, "$..price") print(d_price)
d_price= jsonpath.jsonpath(json_data, ”$..price")的意思是:从根节点($表示跟节点),模糊匹配含有price的键值对的值(..表示模糊匹配)
运行结果如下:
[16.8, 15.8, 13.66, 12.9, 12.9]
jsonpath 和 xpath一样:
json --> jsonpath
xml --> xpath
使用$..XXX 可以找到任何想找到的内容,是一种暴力的方法,为了灵活使用,需要细读并了解