接口自动化多层嵌套的json数据处理

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

def get_dict_value(date, keys, default=None):
    #default=None,在key值不存在的情况下,返回None
    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
posted @ 2019-03-30 15:17  yoyo008  阅读(1272)  评论(0编辑  收藏  举报