Python-接口diff

该文章介绍了一种针对接口返回的复杂JSON数据进行校验的方案。它涉及对嵌套的dict和list的递归比较,通过保存基准(baseline)JSON并比较新响应来检测差异。当发现不同之处时,会记录详细的差异信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

任务背景是接口请求的response中包含了一个大json,需要完整地去校验整个json是否正确(将第一次接口返回的json保存下来,作为baseline,去比对)

难点: json套数组,数组里又有子json串,子json串中又有数组。

方案如下,仅供参考


import json
import os
# 一个从文件里面读取
old = json.load(open('course-studentdata.json', 'r', encoding="utf-8"))

curl = '''从浏览器里copy出来的curl 直接贴进来就成。
curl 'xxxxxxxxxxxxxxxxx
'''
# 一个从接口读取
new = json.loads(os.popen(curl).read())
# 这两个是url,每次取都不一样,需要跳过
filter_field = ["字段1","字段1"]
def checkDict(old_res, new_res):
    diff_result = {}
    for k, v in old_res.items():
        if isinstance(v, dict):
            #print(v)
            flag, diffs = checkDict(v, new_res[k])

            if flag == 1:
                return flag, diffs
        elif isinstance(v, list):
            #print(v)
            if k in filter_field:
                continue
            flag, diffs1 = checkList(v, new_res[k])
            if flag == 1:
                return flag, diffs1
        elif isinstance(v, int):
            if v == new_res[k]:
                continue
            else:
                diff_result[k] = {"old": v, "new": new_res[k]}
                return 1, diff_result
        else:
            if k in filter_field:
                continue
            if k in new_res:
                if v == new_res[k]:
                    continue
                else:
                    diff_result[k] = {"old": v, "new": new_res[k]}
                    return 1, diff_result
            else:
                diff_result[k] = {"msg": "接口返回key不存在:%s" % (k)}
                return 1, diff_result
    return 0, ""

def checkList(old_res, new_res):

    if old_res == [] and new_res == []:
        return 0, ""
    for i in range(len(old_res)):
        if isinstance(old_res[i], dict):
            flag, diffs = checkDict(old_res[i], new_res[i])
            if flag == 1:
                return flag, diffs
        elif isinstance(old_res[i], list):
            flag, diffs1 = checkList(old_res[i], new_res[i])
            if flag == 1:
                return flag, diffs1
        else:
            if old_res[i] == new_res[i]:
                continue
            else:
                diff_result = {"old": old_res[i], "new": new_res[i]}
                return 1, diff_result
    return 0, ""

res = checkDict(old,new)
print(res)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值