1.jsonpath为第三方模块,需要安装,安装命令为:pip install jsonpath
    2.jsonpath主要是用于字典取值,直接使用jsonpath.jsonpath(d,”$.code”)即可取值
    (1)只取第一个:$.string
    (2)取全部:$..string

    1. import jsonpath
    2. d=d={
    3. "code": 200,
    4. "message": "成功!",
    5. "result": {
    6. "code":2001,
    7. "path": "https://www.163.com/dy/article/G1OBC8LO0514BCL4.html",
    8. "image": "http://dingyue.ws.126.net/2021/0201/b63f2e50j00qntwfh0020c000hs00npg.jpg?imageView&thumbnail=140y88&quality=85",
    9. "title": "被指偷拿半卷卫生纸 63岁女洗碗工服药自杀 酒店回应",
    10. "l":[{"msg":"111","money":1}]
    11. }
    12. }
    13. print(jsonpath.jsonpath(d,"$.code")) #[200]
    14. print(jsonpath.jsonpath(d,"$..code")) #[200, 2001]

    3.函数封装

    1. def get_dict_value(dict,target,one=True):
    2. '''
    3. :param dict: 被取值字典
    4. :param target: 目标字段
    5. :param one: 用于判断取一条还是1多条
    6. :return: 取到的字典的值
    7. '''
    8. dict_target="$..%s"%target
    9. data=jsonpath.jsonpath(dict,dict_target)
    10. if not data:
    11. return
    12. if one:
    13. return data
    14. return data[0]
    15. if __name__ == '__main__':
    16. d={"name":"lxp",'age':30,"info":{'name':"lala","age":20}}
    17. ret=get_dict_value(d,"name",True)
    18. print(ret)