Created
December 16, 2013 17:19
-
-
Save mckabi/7990669 to your computer and use it in GitHub Desktop.
My JSON Encoder & Decoder
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
import json | |
def convert(obj): | |
if isinstance(obj, dict): | |
return dict((convert(key), convert(value)) for key, value in obj.iteritems()) | |
elif isinstance(obj, list): | |
return [convert(element) for element in obj] | |
elif isinstance(obj, unicode): | |
return obj.encode('utf-8') | |
else: | |
return obj | |
class JSONEncoder(json.JSONEncoder): | |
def default(self, obj): | |
if isinstance(obj, datetime.datetime): | |
return DateTimeConverter(None).to_url(obj) | |
if isinstance(obj, datetime.timedelta): | |
return str(obj) | |
if isinstance(obj, long): | |
return str(obj) | |
if isinstance(obj, type): | |
return repr(obj) | |
if callable(getattr(obj, 'as_od', None)): | |
return obj.as_od() | |
if callable(getattr(obj, 'as_dict', None)): | |
return obj.as_dict() | |
return super(JSONEncoder, self).default(obj) | |
class JSONDecoder(json.JSONDecoder): | |
def __init__(self, *args, **kwargs): | |
args = list(args) | |
if len(args) >= 2: | |
if args[0] == None: | |
args[0] == 'utf-8' | |
if args[1] == None: | |
args[1] = convert | |
else: | |
if 'encoding' not in kwargs: | |
kwargs['encoding'] = 'utf-8' | |
if 'object_hook' not in kwargs: | |
kwargs['object_hook'] = convert | |
super(JSONDecoder, self).__init__(*args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment