1.jsonpath为第三方模块,需要安装,安装命令为:pip install jsonpath
2.jsonpath主要是用于字典取值,直接使用jsonpath.jsonpath(d,”$.code”)即可取值
(1)只取第一个:$.string
(2)取全部:$..string
import jsonpathd=d={"code": 200,"message": "成功!","result": {"code":2001,"path": "https://www.163.com/dy/article/G1OBC8LO0514BCL4.html","image": "http://dingyue.ws.126.net/2021/0201/b63f2e50j00qntwfh0020c000hs00npg.jpg?imageView&thumbnail=140y88&quality=85","title": "被指偷拿半卷卫生纸 63岁女洗碗工服药自杀 酒店回应","l":[{"msg":"111","money":1}]}}print(jsonpath.jsonpath(d,"$.code")) #[200]print(jsonpath.jsonpath(d,"$..code")) #[200, 2001]
3.函数封装
def get_dict_value(dict,target,one=True):''':param dict: 被取值字典:param target: 目标字段:param one: 用于判断取一条还是1多条:return: 取到的字典的值'''dict_target="$..%s"%targetdata=jsonpath.jsonpath(dict,dict_target)if not data:returnif one:return datareturn data[0]if __name__ == '__main__':d={"name":"lxp",'age':30,"info":{'name':"lala","age":20}}ret=get_dict_value(d,"name",True)print(ret)
