Completed JSON importer. Exported from import matches original data, must be working
This commit is contained in:
parent
7f9e5dbf65
commit
03ce460181
3 changed files with 55 additions and 2 deletions
|
@ -94,6 +94,7 @@ def json_dumps(records):
|
|||
import decimal
|
||||
|
||||
class JSONEncoder(json.JSONEncoder):
|
||||
|
||||
def default(self, o):
|
||||
if hasattr(o, 'toJSON') and callable(getattr(o, 'toJSON')):
|
||||
return o.toJSON()
|
||||
|
@ -108,13 +109,31 @@ def json_dumps(records):
|
|||
|
||||
def json_loads(s, record_classes):
|
||||
import json
|
||||
import fields
|
||||
import decimal
|
||||
import re
|
||||
|
||||
if not isinstance(record_classes, dict):
|
||||
record_classes = dict([ (x.__class__.__name__, x) for x in record_classes])
|
||||
|
||||
def object_hook(o):
|
||||
return {'object_hook':str(o)}
|
||||
if '__class__' in o:
|
||||
klass = o['__class__']
|
||||
|
||||
if klass in record_classes:
|
||||
return record_classes[klass]().fromJSON(o)
|
||||
|
||||
elif hasattr(fields, klass):
|
||||
return getattr(fields, klass)().fromJSON(o)
|
||||
|
||||
return o
|
||||
|
||||
#print "OBJECTHOOK", str(o)
|
||||
#return {'object_hook':str(o)}
|
||||
#def default(self, o):
|
||||
# return super(JSONDecoder, self).default(o)
|
||||
|
||||
return json.loads(s, object_hook=object_hook)
|
||||
return json.loads(s, parse_float=decimal.Decimal, object_hook=object_hook)
|
||||
|
||||
# THIS WAS IN CONTROLLER, BUT UNLESS WE
|
||||
# REALLY NEED A CONTROLLER CLASS, IT'S SIMPLER
|
||||
|
|
|
@ -62,6 +62,21 @@ class Field(object):
|
|||
'dataLength': len(data)
|
||||
}
|
||||
|
||||
def fromJSON(self, o):
|
||||
import re
|
||||
|
||||
self.__init__(
|
||||
name=o['name'],
|
||||
max_length=o['maxLength'],
|
||||
required=o['required'],
|
||||
)
|
||||
|
||||
if isinstance(o['value'], basestring) and re.match('^\d*\.\d*$', o['value']):
|
||||
o['value'] = decimal.Decimal(o['value'])
|
||||
|
||||
self.value = o['value']
|
||||
return self
|
||||
|
||||
|
||||
class TextField(Field):
|
||||
def validate(self):
|
||||
|
|
|
@ -73,3 +73,22 @@ class Model(object):
|
|||
'fields': self.get_sorted_fields()
|
||||
}
|
||||
|
||||
def fromJSON(self, o):
|
||||
fields = o['fields']
|
||||
|
||||
for f in fields:
|
||||
target = self.__dict__[f.name]
|
||||
|
||||
if (target.required != f.required or
|
||||
target.max_length != f.max_length):
|
||||
print "Warning: value mismatch on import"
|
||||
|
||||
target._value = f._value
|
||||
|
||||
|
||||
#print (self.__dict__[f.name].name == f.name)
|
||||
#self.__dict__[f.name].name == f.name
|
||||
#self.__dict__[f.name].max_length == f.max_length
|
||||
|
||||
return self
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue