python对两个json文件排序并判断两个json文件是否相等

方法1:递归比较每一个字段。
缺点:对jsonArray中每个字段需要特殊处理并排序。

# -*-coding:utf-8-*-
import json
import jsonpatch
import sys


def cmp(src_data, dst_data):
    if isinstance(src_data, dict):
        """若为dict格式"""
        for key in dst_data:
            if key not in src_data:
                print("src不存在这个key:" + key)
                return False
        for key in src_data:
            if key in dst_data:
                thiskey = key
                """递归"""
                # if key == "nrfProfileId":
                #     continue
                # else:
                if cmp(src_data[key], dst_data[key]) is False:
                    return False
            else:
                print("dst不存在这个key:" + key)
                return False
    elif isinstance(src_data, list):
        """若为list格式"""
        if len(src_data) != len(dst_data):
            print("list len: '{}' != '{}'".format(len(src_data), len(dst_data)))
            return False
        if "fqdn" in src_data[0]:
            src_data.sort(key=lambda x: x["fqdn"])
            dst_data.sort(key=lambda x: x["fqdn"])
        elif "nrfProfileId" in src_data[0]:
            src_data.sort(key=lambda x: x["nrfProfileId"])
            dst_data.sort(key=lambda x: x["nrfProfileId"])
        for src_list, dst_list in zip(src_data, dst_data):
            """递归"""
            if cmp(src_list, dst_list) is False:
                return False
    else:
        if str(src_data) != str(dst_data):
            print("src_data: '{}' != dst_data: '{}'".format(src_data, dst_data))
            return False
    return True


def comparetwojson(real_json, except_json):
    if len(real_json) == len(except_json):
        for j in range(len(except_json)):
            exp_profile = except_json[j]
            i = 0
            for i in range(len(real_json)):
                profile = real_json[i]

                p_patch = jsonpatch.JsonPatch.from_diff(profile, exp_profile)

                if list(p_patch) == []:
                    i -= 1
                    print("GRPC message return profile list is the \
                                    same as the expected profile list")
                    break

            if i == len(real_json) - 1:
                return False
        return True

    else:
        return False


if __name__ == "__main__":
    xx = {"111": None,
          "23456": {"33333": "0000", "22222": 9999}}

    yy = {"111": None,
          "23456": {"22222": 9999, "33333": "0000"}}
    x1 = [{"nrfProfileId": "12345678-provision-0001", "servingPlmn": {"mcc": "310", "mnc": "003"},
           "nrfAddresses": [{"scheme": "http", "fqdn": "192.168.240.9", "port": 5678}]},
          {"nrfProfileId": "12345678-provision-0002", "servingPlmn": {"mcc": "310", "mnc": "003"},
           "nrfAddresses": [{"scheme": "http", "fqdn": "www.baidu.com", "port": 5002},
                            {"scheme": "http", "fqdn": "150.132.165.200", "port": 5003}]}]
    x2 = [{"nrfProfileId": "12345678-provision-0001", "servingPlmn": {"mcc": "310", "mnc": "003"},
           "nrfAddresses": [{"scheme": "http", "fqdn": "192.168.240.9", "port": 5678}]},
          {"nrfProfileId": "12345678-provision-0002", "servingPlmn": {"mnc": "003", "mcc": "310"},
           "nrfAddresses": [{"scheme": "http", "fqdn": "150.132.165.200", "port": 5003},
                            {"scheme": "http", "fqdn": "www.baidu.com", "port": 5002}]}]

    y1 = json.load(open(sys.argv[1]))
    y2 = json.load(open(sys.argv[2]))
    if cmp(y1, y2):
        print("equal")
    else:
        print("not equal")

    # if comparetwojson(x1, x2):
    #     print("相等")
    # else:
    #     print("不相等")

方法2:对dict和list对象的json分别进行排序
优点:代码简洁通用。

def ordered(obj):
    if isinstance(obj, dict):
        return sorted((k, ordered(v)) for k, v in obj.items())
    if isinstance(obj, list):
        return sorted(ordered(x) for x in obj)
    else:
        return obj
if __name__ == "__main__":
    xx = {"111": None,
          "23456": {"33333": "0000", "22222": 9999}}

    yy = {"111": None,
          "23456": {"22222": 9999, "33333": "0000"}}
    x1 = [{"nrfProfileId": "12345678-provision-0001", "servingPlmn": {"mcc": "310", "mnc": "003"},
           "nrfAddresses": [{"scheme": "http", "fqdn": "192.168.240.9", "port": 5678}]},
          {"nrfProfileId": "12345678-provision-0002", "servingPlmn": {"mcc": "310", "mnc": "003"},
           "nrfAddresses": [{"scheme": "http", "fqdn": "www.baidu.com", "port": 5002},
                            {"scheme": "http", "fqdn": "150.132.165.200", "port": 5003}]}]
    x2 = [{"nrfProfileId": "12345678-provision-0001", "servingPlmn": {"mcc": "310", "mnc": "003"},
           "nrfAddresses": [{"scheme": "http", "fqdn": "192.168.240.9", "port": 5678}]},
          {"nrfProfileId": "12345678-provision-0002", "servingPlmn": {"mnc": "003", "mcc": "310"},
           "nrfAddresses": [{"scheme": "http", "fqdn": "150.132.165.200", "port": 5003},
                            {"scheme": "http", "fqdn": "www.baidu.com", "port": 5002}]}]
    print(ordered(x1))
    print(ordered(x2))
    print(ordered(x1)==ordered(x2))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值