python_jsonpath方法
jsonpath提供了在多维字典中找到某个key的便捷方法,一定要知道哦~
用法如下:
import jsonpath
#这是一个复杂的json串 d={ "code": 200, "message": "成功!", "result": [{ "sid": "29668676", "text": "假如员工比老板有钱", "type": "video", "thumbnail": "http://wimg.spriteapp.cn/picture/2019/0719/5d3140efefed1_wpd.jpg", "video": "http://uvideo.spriteapp.cn/video/2019/0719/5d3140efefed1_wpd.mp4", "up": "106", "down": "8", "forward": "2", "comment": "6", "uid": "20272202", "name": "淼兔兔i", "header": "http://wimg.spriteapp.cn/profile/large/2018/04/19/5ad85b1dc8973_mini.jpg", "passtime": "2019-07-21 02:55:02" }, { "sid": "29640878", "text": "各大老陈醋厂家即将面临史上最大威胁", "type": "video", "thumbnail": "http://wimg.spriteapp.cn/picture/2019/0708/5d23510ce5a84_wpd.jpg", "video": "http://uvideo.spriteapp.cn/video/2019/0708/5d23510ce5a84_wpd.mp4", "up": "294", "down": "6", "forward": "0", "comment": "21", "uid": "23133772", "name": "雪碧与可乐", "header": "http://wimg.spriteapp.cn/profile/large/2019/07/04/5d1da0563a951_mini.jpg", "passtime": "2019-07-21 02:15:01" }] }
#如果我们需要找到video的值,传统方法是 print(d[result][0][video]) #使用jsonpath result=jsonpath.jsonpath(d,'$..video') #$代表最外层,无论这个key的位置在哪里都能找到。如果对应的是多个Key,那么返回的是一个list
d2 = { "stu":{ "sex":'男', "house":{ "bejing":{"四环":5,"三环":4}, "上海":{"浦东":4} } } } print(d2['stu']['house']['上海']['浦东']) result2=jsonpath.jsonpath(d2,'$..浦东') #无论这个key的位置在哪里都能找到 result3=jsonpath.jsonpath(d2,'$.stu.house')#$代表最外层,可以一直点下去
#如果找不到对应的key,返回结果是False