added json encoder and partially functioning json decoder

This commit is contained in:
Binh 2013-05-14 13:48:48 -05:00
parent b9982c3a21
commit 7f9e5dbf65
3 changed files with 50 additions and 0 deletions

View file

@ -88,6 +88,33 @@ def dumps(records):
fp.seek(0)
return fp.read()
def json_dumps(records):
import json
import model
import decimal
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if hasattr(o, 'toJSON') and callable(getattr(o, 'toJSON')):
return o.toJSON()
elif isinstance(o, decimal.Decimal):
return str(o.quantize(decimal.Decimal('0.01')))
return super(JSONEncoder, self).default(o)
return json.dumps(records, cls=JSONEncoder, indent=2)
def json_loads(s, record_classes):
import json
def object_hook(o):
return {'object_hook':str(o)}
#def default(self, o):
# return super(JSONDecoder, self).default(o)
return json.loads(s, object_hook=object_hook)
# THIS WAS IN CONTROLLER, BUT UNLESS WE
# REALLY NEED A CONTROLLER CLASS, IT'S SIMPLER
@ -104,6 +131,7 @@ def validate_required_records(records):
while req_types:
req = req_types[0]
if req not in types:
from fields import ValidationError
raise ValidationError("Record set missing required record: %s" % req)
else:
req_types.remove(req)