Shayan
Shayan

Reputation: 548

Python Check if two list of jsons are equal

I have two list of JSON objects:

[{u'amount': 12000, u'address': u'mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f'},
 {u'amount': 1000, u'address': u'mkVuZV2kVtMzddQabFDanFi6DTwWYtgiCn'}]

[{"amount": 12000, "address": "mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f"},
 {"amount": 1000, "address": "mkVuZV2kVtMzddQabFDanFi6DTwWYtgiCn"}]

They might come in different orders, or one might be a subset of the other or just different addresses, I need a function to just say True if both include the same addresses/amounts or False if they are different.

I guess the problem is one has unicode keys/values but the other ones are strings.

I've spent too much time on this simple issue that have no clue what else to do.

Upvotes: 0

Views: 344

Answers (2)

Shayan
Shayan

Reputation: 548

so in the end this is what I wrote, might not be the most efficient way but it works!

def json_equal(json1,json2):

   number_of_items = len(json1)
   for item in json1:
       for item2 in json2:
           if item["address"] == item2["address"]:
               if item["amount"] == item2["amount"]:
                   number_of_items -= 1
                   break
           else:
               continue
   if number_of_items == 0:
       return True
   else:
       return False

Upvotes: 0

Óscar López
Óscar López

Reputation: 236004

The trick here is to use a data structure that ignores the order in which elements appear when performing an equality comparison - say, a set. Try this, which uses set comprehensions for extracting the addresses and amounts from each list:

{(d['address'], d['amount']) for d in lst1} == {(d['address'], d['amount']) for d in lst2}

Upvotes: 2

Related Questions