support datetime in json serialization

This commit is contained in:
j 2011-02-25 00:55:07 +01:00
parent 2132510a8c
commit 9043418608
2 changed files with 23 additions and 10 deletions

View file

@ -1,24 +1,30 @@
import time import time
import datetime
from django.db import models from django.db import models
from ox.utils import json from ox.utils import json
def to_json(python_object): def to_json(python_object):
if isinstance(python_object, time.struct_time):
return {'__class__': 'time.asctime',
'__value__': time.asctime(python_object)}
if isinstance(python_object, bytes): if isinstance(python_object, bytes):
return {'__class__': 'bytes', return {'__class__': 'bytes',
'__value__': list(python_object)} '__value__': list(python_object)}
if isinstance(python_object, datetime.datetime):
return {'__class__': 'datetime.datetime',
'__value__': python_object.strftime('%Y-%m-%dT%H:%M:%SZ')}
if isinstance(python_object, time.struct_time):
return {'__class__': 'time.asctime',
'__value__': time.asctime(python_object)}
raise TypeError(repr(python_object) + ' is not JSON serializable') raise TypeError(repr(python_object) + ' is not JSON serializable')
def from_json(json_object): def from_json(json_object):
if '__class__' in json_object: if '__class__' in json_object:
if json_object['__class__'] == 'time.asctime':
return time.strptime(json_object['__value__'])
if json_object['__class__'] == 'bytes': if json_object['__class__'] == 'bytes':
return bytes(json_object['__value__']) return bytes(json_object['__value__'])
if json_object['__class__'] == 'datetime.datetime':
return datetime.datetime.strptime(json_object['__value__'], '%Y-%m-%dT%H:%M:%SZ')
if json_object['__class__'] == 'time.asctime':
return time.strptime(json_object['__value__'])
return json_object return json_object
class DictField(models.TextField): class DictField(models.TextField):

View file

@ -1,5 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4 # vi:si:et:sw=4:sts=4:ts=4
from datetime import datetime
from django.http import HttpResponse, Http404 from django.http import HttpResponse, Http404
try: try:
import simplejson as json import simplejson as json
@ -16,6 +17,11 @@ def json_response(data=None, status=200, text='ok'):
data = {} data = {}
return {'status': {'code': status, 'text': text}, 'data': data} return {'status': {'code': status, 'text': text}, 'data': data}
def _to_json(python_object):
if isinstance(python_object, datetime):
python_object.strftime('%Y-%m-%dT%H:%M:%SZ')
raise TypeError(repr(python_object) + ' is not JSON serializable')
def render_to_json_response(dictionary, content_type="text/json", status=200): def render_to_json_response(dictionary, content_type="text/json", status=200):
indent=None indent=None
if settings.DEBUG: if settings.DEBUG:
@ -25,7 +31,8 @@ def render_to_json_response(dictionary, content_type="text/json", status=200):
print json.dumps(dictionary, indent=2) print json.dumps(dictionary, indent=2)
if 'status' in dictionary and 'code' in dictionary['status']: if 'status' in dictionary and 'code' in dictionary['status']:
status = dictionary['status']['code'] status = dictionary['status']['code']
return HttpResponse(json.dumps(dictionary, indent=indent),
return HttpResponse(json.dumps(dictionary, indent=indent, default=_to_json),
content_type=content_type, status=status) content_type=content_type, status=status)
def get_object_or_404_json(klass, *args, **kwargs): def get_object_or_404_json(klass, *args, **kwargs):