Last active
August 29, 2015 14:09
-
-
Save andreasvc/61254b40830eb180f475 to your computer and use it in GitHub Desktop.
Unordered equality test of JSON data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Convert JSON to an immutable representation so that equality can be tested | |
without regard for order.""" | |
import json | |
class decoder(json.JSONDecoder): | |
# http://stackoverflow.com/questions/10885238/python-change-list-type-for-json-decoding | |
def __init__(self, list_type=list, **kwargs): | |
json.JSONDecoder.__init__(self, **kwargs) | |
# Use the custom JSONArray | |
self.parse_array = self.JSONArray | |
# Use the python implemenation of the scanner | |
self.scan_once = json.scanner.py_make_scanner(self) | |
self.list_type = list_type | |
def JSONArray(self, s_and_end, scan_once, **kwargs): | |
values, end = json.decoder.JSONArray(s_and_end, scan_once, **kwargs) | |
return self.list_type(values), end | |
class JsonSetEncoder(json.JSONEncoder): | |
"""Convert sets to lists for JSON encoding.""" | |
def default(self, obj): # pylint: disable=method-hidden | |
"""Do conversion.""" | |
if isinstance(obj, frozenset): | |
result = list(obj) | |
if result and isinstance(result[0], tuple) and len(result[0]) == 2: | |
return dict(result) | |
return result | |
return json.JSONEncoder.default(self, obj) | |
def itemset(d): | |
"""Convert dictionary to set of tuples.""" | |
return frozenset(d.items()) | |
answerA = """{"answer": {"selections": [[{"start":0, "end":5, "extent": | |
"Dalla", "word_index":0}], [{"start":0, "end":11, "extent":"provenivano", | |
"word_index":2}], [{"start":0,"end":6,"word_index":3,"extent":"strani"}, | |
{"start":0,"end":6,"extent":"rumori","word_index":4}]]}}""" | |
answerB = """{"answer":{"selections":[[{"start":0,"end":11,"extent": | |
"provenivano","word_index":2}],[{"start":0,"end":5,"extent":"Dalla", | |
"word_index":0}],[{"start":0,"end":6,"word_index":3,"extent":"strani"}, | |
{"start":0,"end":6,"extent":"rumori","word_index":4}]]}}""" | |
jsonA = json.loads(answerA) | |
jsonB = json.loads(answerB) | |
print jsonA == jsonB | |
jsonA = json.loads(answerA, cls=decoder, | |
list_type=frozenset, object_hook=itemset) | |
jsonB = json.loads(answerB, cls=decoder, | |
list_type=frozenset, object_hook=itemset) | |
print jsonA == jsonB | |
print jsonA | |
print jsonB | |
print json.dumps(jsonA, cls=JsonSetEncoder, indent=2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment