Serializer.py 831 Bytes
Newer Older
jtchilders's avatar
jtchilders committed
1
import json,logging,datetime
jtchilders's avatar
jtchilders committed
2 3 4
logger = logging.getLogger(__name__)


jtchilders's avatar
jtchilders committed
5 6 7
def serialize(obj,sort_keys=False,pretty_print=None,use_datetime=True):
   if use_datetime:
      return json.dumps(obj,sort_keys=sort_keys,indent=pretty_print,cls=DateTimeEncoder)
jtchilders's avatar
jtchilders committed
8 9 10 11 12 13 14 15 16 17
   return json.dumps(obj,sort_keys=sort_keys,indent=pretty_print)

def deserialize(text):
   #logger.debug(' Deserializing: \n' + text)
   return json.loads(text)

def convert_unicode_string(unicode_string):
   if unicode_string is not None:
      return str(unicode_string)
   return None
jtchilders's avatar
jtchilders committed
18 19 20 21 22 23 24

class DateTimeEncoder(json.JSONEncoder):
     def default(self, obj):
         if isinstance(obj, datetime.datetime):
             return obj.strftime("%Y-%m-%d %H:%M:%S %z")
         # Let the base class default method raise the TypeError
         return json.JSONEncoder.default(self, obj)