Open natrayanp opened 6 years ago
Compare 2 JSON array and return non matching with the base:
predict = {'eggs': [{'name': 2,"address":"pasir 2"},{'name': 2,"address":"pasir 2"}],'ham': [{'name': 1,"address":"pasir 1"},{'name': 2,"address":"pasir 2"},{'name': 3,"address":"pasir 3"}]} actual = {'eggs': [{'name': 2,"address":"pasir 2"}], 'ham': [{'name': 1,"address":"pasir 1"},{'name': 2,"address":"pasir 2"}]} difference = {} for key, value in predict.items(): difference[key] = [el for el in predict[key] if (key not in actual) or (el not in actual[key])] print(difference)
To check if the 2 JSON are equal or not:
a = json.loads(""" { "errors": [ {"error": "invalid", "field": "email"}, {"error": "required", "field": "name"} ], "success": false } """)
b = json.loads(""" { "success": false, "errors": [ {"error": "required", "field": "name"}, {"error": "invalid", "field": "email"} ] } """)
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 we apply this function to a and b, the results compare equal:
ordered(a) == ordered(b)
https://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches
Compare 2 arrays:
set(a).intersection(b) set(a).difference(b)