接口自动化多层嵌套json数据处理代码实例

Ianthe ·
更新时间:2024-09-20
· 916 次阅读

最近在做接口自动化测试,响应的内容大多数是多层嵌套的json数据,在对响应数据进行校验的时候,可以通过(key1.key2.key3)形式获取嵌套字典值的方法获取响应值,再和预期值比较

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类型的字符串。

有个朋友分享过这段代码,大家可以试试。

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 您可能感兴趣的文章:python 调用API接口 获取和解析 Json数据为什么rest接口返回json建议采用下划线形式,不要用驼峰Django+RestFramework API接口及接口文档并返回json数据操作IOS-MVC层读取服务器接口JSON数据vue-resource:jsonp请求百度搜索的接口示例laravel 错误处理,接口错误返回json代码spring boot 统一JSON格式的接口返回结果的实现微信小程序如何调用json数据接口并解析



接口自动化 自动 自动化 json数据 JSON 接口

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章