Skip to content

Instantly share code, notes, and snippets.

@igorcoding
Created August 18, 2016 18:38
Show Gist options
  • Save igorcoding/eaee1c678f1301452f8f360832a75e71 to your computer and use it in GitHub Desktop.
Save igorcoding/eaee1c678f1301452f8f360832a75e71 to your computer and use it in GitHub Desktop.
class CustomJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, JsonSerializable):
return obj.__to_json__()
if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date):
return int(time.mktime(obj.timetuple()))
return super(CustomJsonEncoder, self).default(obj)
class JsonSerializable:
@abc.abstractmethod
def __to_json__(self):
raise NotImplementedError()
def json_dumps(obj, compact=True, **kwargs):
kwargs['cls'] = kwargs.get('cls', CustomJsonEncoder)
kwargs['ensure_ascii'] = kwargs.get('ensure_ascii', False)
if compact:
kwargs['separators'] = (',', ':')
return json.dumps(obj, **kwargs)
def json_loads(obj, **kwargs):
kwargs['encoding'] = kwargs.get('encoding', 'utf-8')
return json.loads(obj, **kwargs)
def ensure_json(obj, **kwargs):
if obj is None:
return None
if isinstance(obj, list) or isinstance(obj, dict):
return obj
return json_loads(obj, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment