Skip to content

Instantly share code, notes, and snippets.

@tr3buchet tr3buchet/serializer.py
Last active Dec 13, 2015

Embed
What would you like to do?
created by github.com/tr3buchet/gister
from datetime import datetime
import time
import json
class A(object):
def __init__(self, wizards=12, goats='A lot', time_stamp=None):
self.wizards = wizards
self.goats = goats
self.time = time_stamp or datetime.now()
def serialize(self):
return {'wizards': self.wizards,
'goats': self.goats,
'time': int(time.mktime(self.time.timetuple()))}
@staticmethod
def deserialize(sd):
if 'wizards' in sd and 'goats' in sd and 'time' in sd:
return A(sd['wizards'], sd['goats'],
datetime.fromtimestamp(sd['time']))
def __str__(self):
return '%s' % {'wizards': self.wizards,
'goats': self.goats, 'time': self.time}
a = A()
some_jsons = json.dumps(a, indent=4, default=lambda obj: obj.serialize())
print some_jsons
some_obj = json.loads(some_jsons, object_hook=A.deserialize)
print some_obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.