0

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.

5
  • 1
    That isn't valid JSON, it looks like the Python dict literal syntax. Commented Apr 2, 2015 at 20:44
  • I printed them out for logging with ("%s - %s" % (outputs, new_outputs)) Commented Apr 2, 2015 at 20:47
  • Do the "amount" entries matter? Commented Apr 2, 2015 at 20:47
  • @Asad yes, the pair matters. even if you swap the amounts for each addresses it should return False Commented Apr 2, 2015 at 20:48

2 Answers 2

2

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}
Sign up to request clarification or add additional context in comments.

4 Comments

the key value should be the same to be True, both address and the amount.
anyhow I'd try a nested if
@Shayanbahal You can just concatenate the address and amount and compare.
@Shayanbahal {(json['address'], json['amount']) for json in lst1} == {(json['address'], json['amount']) for json in lst2}
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.