Created
May 29, 2015 15:48
-
-
Save reidransom/75927abacecabde58903 to your computer and use it in GitHub Desktop.
Normalize any object for json serialization
This file contains 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
class NormalizeData(object): | |
SERIALIZABLE_TYPES = [str, int, bool, float, list, dict, type(None)] | |
def __init__(self, element): | |
self.element = element | |
def execute(self): | |
if isinstance(self.element, dict): | |
self.iterate_dict() | |
if isinstance(self.element, list): | |
self.iterate_list() | |
else: | |
return | |
def normalize(self, el): | |
#if isinstance(el, <ClassName>): | |
# # Do custom serialization here | |
# return el | |
# Check if the object has a `__norm()` function for custom normalization. | |
if hasattr(el, '__norm'): | |
return el.__norm() | |
if type(el) not in self.SERIALIZABLE_TYPES: | |
return str(el) | |
return el | |
def iterate_list(self): | |
for i in range(len(self.element)): | |
self.element[i] = self.normalize(self.element[i]) | |
node = NormalizeData(self.element[i]) | |
node.execute() | |
def iterate_dict(self): | |
for key in self.element: | |
self.element[key] = self.normalize(self.element[key]) | |
node = NormalizeData(self.element[key]) | |
node.execute() | |
def dumps(data): | |
""" JSON serialize any object. | |
""" | |
norm = NormalizeData(data) | |
norm.execute() | |
try: | |
return json.dumps(norm.element) | |
except TypeError: | |
# `data` itself is a non-serializable object | |
return str(norm.element) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment