Skip to content

Commit

Permalink
closes #3. if an object has an datetime.date attribute it will now be…
Browse files Browse the repository at this point in the history
… able to serialize this correctly.
  • Loading branch information
steenzout committed Nov 30, 2016
1 parent f1a2191 commit d9c4a6b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 17 deletions.
28 changes: 17 additions & 11 deletions steenzout/serialization/json/encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"""JSON encoders module."""

import calendar
import datetime
import inspect
import logging
import strict_rfc3339
Expand All @@ -40,19 +41,24 @@ def as_object(obj):
"""
LOGGER.debug('as_object(%s)', obj)

# populate dict with visible attributes
out = {k: obj.__dict__[k] for k in obj.__dict__ if not k.startswith('_')}
if isinstance(obj, datetime.date):
return as_date(obj)

# populate dict with property names and values
for k, v in (
(p, getattr(obj, p))
for p, _ in inspect.getmembers(
obj.__class__,
lambda x: isinstance(x, property))
):
out[k] = v
elif hasattr(obj, '__dict__'):

return out
# populate dict with visible attributes
out = {k: obj.__dict__[k] for k in obj.__dict__ if not k.startswith('_')}

# populate dict with property names and values
for k, v in (
(p, getattr(obj, p))
for p, _ in inspect.getmembers(
obj.__class__,
lambda x: isinstance(x, property))
):
out[k] = v

return out


def as_date(dat):
Expand Down
21 changes: 15 additions & 6 deletions tests/json_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,16 +81,25 @@ def test_serialize_object(self):
"""Test serialize() function."""

class A(Object):
def __init__(self, x=None, y=None):
def __init__(self, x=None, y=None, d=None):
self.x = x
self.y = y
self.d = d

result = json.serialize(A(1, 2))
self.assertTrue(
'{"x": 1, "y": 2}' == result or
'{"y": 2, "x": 1}' == result,
'result=%s' % result
now = datetime.now()
now_rfc3339 = strict_rfc3339.timestamp_to_rfc3339_utcoffset(
calendar.timegm(now.timetuple())
)
result = json.serialize(A(1, 2, now))
result_dict = eval(result)

assert len(result_dict) == 3
assert 'x' in result_dict
assert result_dict['x'] == 1
assert 'y' in result_dict
assert result_dict['y'] == 2
assert 'd' in result_dict
assert result_dict['d'] == now_rfc3339

def test_serialize_object_with_properties(self):
"""Test serialize() function with object with properties."""
Expand Down

0 comments on commit d9c4a6b

Please sign in to comment.