最近在做接口自动化测试,响应的内容大多数是多层嵌套的json数据,在对响应数据进行校验的时候,可以通过(key1.key2.key3)形式获取嵌套字典值的方法获取响应值,再和预期值比较
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | keys_list = keys.split('.') #以“.”为间隔,将字符串分裂为多个字符串,其实字符串为字典的键,保存在列表keys_list里 if isinstance(date,dict): #如果传入的数据为字典 dictionary = dict(date) #初始化字典 for i in keys_list: #按照keys_list顺序循环键值 try: if dictionary.get(i) != None: dict_values = dictionary.get(i) #如果键对应的值不为空,返回对应的值 elif dictionary.get(i) == None: dict_values = dictionary.get(int(i)) #如果键对应的值为空,将字符串型的键转换为整数型,返回对应的值 except: return default #如果字符串型的键转换整数型错误,返回None dictionary = dict_values return dictionary else: #如果传入的数据为非字典 try: dictionary = dict(eval(date)) #如果传入的字符串数据格式为字典格式,转字典类型,不然返回None if isinstance(dictionary,dict): for i in keys_list: #按照keys_list顺序循环键值 try: if dictionary.get(i) != None: dict_values = dictionary.get(i) #如果键对应的值不为空,返回对应的值 elif dictionary.get(i) == None: dict_values = dictionary.get(int(i)) #如果键对应的值为空,将字符串型的键转换为整数型,返回对应的值 except: return default #如果字符串型的键转换整数型错误,返回None dictionary = dict_values return dictionary except: return default |
运行结果:
一:字典类型数据。

二:字典类型数据,包含的键为数字。

三:json类型的字符串。

有个朋友分享过这段代码,大家可以试试。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class obj(object): def __init__(self, d): for a, b in d.items(): if isinstance(b, (list, tuple)): setattr(self, a, [obj(x) if isinstance(x, dict) else x for x in b]) else: setattr(self, a, obj(b) if isinstance(b, dict) else b) d = {'a':1, 'b':{'c':2}, 'd':[{'e':1}]} res = obj(d) print res.a print res.b.c print res.d[0].e |
现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。
如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受
可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛
分享他们的经验,还会分享很多直播讲座和技术沙龙
可以免费学习!划重点!开源的!!!
qq群号:485187702【暗号:csdn11】
最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走! 希望能帮助到你!【100%无套路免费领取】

