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))

你可能感兴趣的:(python)