与python中对象之间不同链接的Json比较



我正在尝试比较 2 个在 ids 值中显示不同顺序的 json,即使它们在本质上是相同的,正如您从示例中看到的那样。

例如,每个 person 对象都基于其 id 指向一个地址对象。ids 可能不同,但可以肯定的是,2 个 json 是相同的。这里有一个例子:address_id的顺序不同(作为地址对象位置(,但 2 个 json 是相同的(John 住在纽约市,Pippo 住在 BCN(。

{
   "Persons": [
     {
       "Name": "John",
       "Address_Id": "0"
     },
     {
       "Name": "Pippo",
       "Address_Id": "1"
     }
   ],
   "Addresses": [
     {
       "City": "NYC"
     },
     {
       "City": "BCN"
     }
   ]
 }

{
   "Persons": [
     {
       "Name": "John",
       "Address_Id": "1"
     },
     {
       "Name": "Pippo",
       "Address_Id": "0"
     }
   ],
   "Addresses": [
     {
       "City": "BCN"
     },
     {
       "City": "NYC"
     }
   ]
 }

考虑到这种"特殊情况",有没有办法比较 2 个 json?

谢谢。

您可以通过创建等效的 Python 类并自己实现比较来自己反序列化 json。.例如:

import json
class Person_book:
    def __init__(self, person_list):
        self.person_list = person_list
    def __eq__(self, other):
        if len(self.person_list) != len(other.person_list):
            return False
        for person in self.person_list:
            if person not in other.person_list:
                return False
        return True
class Person:
    def __init__(self, person_id, address):
        self.person_id = person_id
        self.address = address
    def __str__(self):
        return str(self.person_id) + ' ' + str(self.address )
    def __eq__(self, other):
        if self.person_id == other.person_id and self.address == other.address:
            return True
        return False
def deserialize_persons(persons_array):
    persons = persons_array['Persons']
    addresses = persons_array['Addresses']
    person_list = []
    for person in persons:
        person_entry = Person(person['Name'], addresses[int(person['Address_Id'])])
        person_list.append(person_entry)
    return Person_book(person_list)
json_resp_1 = """{
   "Persons": [
     {
       "Name": "John",
       "Address_Id": "0"
     },
     {
       "Name": "Pippo",
       "Address_Id": "1"
     }
   ],
   "Addresses": [
     {
       "City": "NYC"
     },
     {
       "City": "BCN"
     }
   ]
 }"""
json_resp_2 = """
{
   "Persons": [
     {
       "Name": "John",
       "Address_Id": "1"
     },
     {
       "Name": "Pippo",
       "Address_Id": "0"
     }
   ],
   "Addresses": [
     {
       "City": "BCN"
     },
     {
       "City": "NYC"
     }
   ]
 }"""
resp_1 = json.loads(json_resp_1)
resp_2 = json.loads(json_resp_2)
person_book_1 = deserialize_persons(resp_1)
person_book_2 = deserialize_persons(resp_2)
print(person_book_1 == person_book_2)

相关内容

  • 没有找到相关文章

最新更新