两个json字符串的对比
2021-06-21 03:04
标签:key instance str compare append format pre ror == 两个json字符串的对比 标签:key instance str compare append format pre ror == 原文地址:https://www.cnblogs.com/laochiji/p/14903530.htmldef verify_data(resdata,expdata,ignorkey=[]):
logging.info("-" * 100)
logging.info("响应数据:{0}".format(resdata))
logging.info("期望数据:{0}".format(expdata))
logging.info("-" * 100)
result_all = []
def compare(resdata,expdata,key):
# 判断他们的类型是否相同
if type(resdata) == type(expdata):
if isinstance(resdata,dict):
# 判断是key否是一致
resdiff = set(resdata.keys()).difference(set(expdata.keys()))
if resdiff:
result_all.append(f"节点:{key} 缺少key-->{resdiff}")
for k in resdata.keys():
key = k
if k not in resdiff and k not in ignorkey:
compare(resdata.get(key),expdata.get(key),key)
elif isinstance(resdata,list):
# 判断长度
if len(resdata) == len(expdata):
for index,values in enumerate(zip(resdata,expdata)):
compare(values[0],values[1],key+str(index))
else:
result_all.append(f"节点:{key} 长度不一致-->res: {resdata}, exp: {expdata}")
else:
if resdata == expdata:
pass
# 期望值填“*” 时忽略
elif expdata == "*":
pass
elif resdata != expdata:
result_all.append(f"节点:{key} 值不一致-->res: {resdata}, exp: {expdata}")
else:
if expdata != "*":
result_all.append(f"节点:{key} 类型不一致-->res: {type(resdata)}, exp: {type(expdata)}")
compare(resdata,expdata,key="root")
if result_all:
logging.error(‘\n‘.join(result_all))
assert result_all == []
else:
assert result_all == []