jazzband / jsonmodels

jsonmodels is library to make it easier for you to deal with structures that are converted to, or read from JSON.
http://jsonmodels.readthedocs.org/en/latest/
BSD 3-Clause "New" or "Revised" License
334 stars 51 forks source link

Fields should handle "to_struct" themselves when parsing #72

Closed johncalls closed 7 years ago

johncalls commented 7 years ago

In the parsers' to_struct method seems to be an issue:

if isinstance(value, list):
    resp[name] = [to_struct(item) for item in value]
else:
    resp[name] = to_struct(value)

In my opinion, this should be handled by each field's to_struct method, e.g.:

if isinstance(value, list):
    resp[name] = [to_struct(item) for item in value]
else:
    resp[name] = field.to_struct(value)

(Additionally, I think ListField should implement it's own to_struct, so the if-case would no longer be necessary here.)

I ran into this issue when trying to handle fields of type DateTimeField:

class ModelWithDate(models.Base):
    date = fields.DateTimeField(required=True)

m = ModelWithDate()
m.date = "2013-05-06 12:03:34"
json.dumps(m.to_struct())

Result: TypeError: datetime.datetime(2013, 5, 6, 12, 3, 34) is not JSON serializable

dimakuz commented 7 years ago

+1

beregond commented 7 years ago

PR merged, but I'm leaving this issue open as 'to be improved' in future (so all fields handle their structure by themselves).