Added datetime, Decimal and set support to JSONSerializer.
This commit is contained in:
parent
7b83e7d663
commit
84ced6c68b
|
@ -3,6 +3,9 @@
|
|||
from __future__ import absolute_import
|
||||
|
||||
from benedict.serializers.abstract import AbstractSerializer
|
||||
from benedict.utils import type_util
|
||||
|
||||
from six import text_type
|
||||
|
||||
import json
|
||||
|
||||
|
@ -16,5 +19,18 @@ class JSONSerializer(AbstractSerializer):
|
|||
|
||||
@staticmethod
|
||||
def encode(d, **kwargs):
|
||||
kwargs.setdefault('default', JSONSerializer._encode_default)
|
||||
data = json.dumps(d, **kwargs)
|
||||
return data
|
||||
|
||||
@staticmethod
|
||||
def _encode_default(obj):
|
||||
if type_util.is_json_serializable(obj):
|
||||
return None
|
||||
elif type_util.is_set(obj):
|
||||
return list(obj)
|
||||
elif type_util.is_datetime(obj):
|
||||
return obj.isoformat()
|
||||
elif type_util.is_decimal(obj):
|
||||
return text_type(obj)
|
||||
return text_type(obj)
|
||||
|
|
|
@ -32,17 +32,24 @@ class dump_test_case(unittest.TestCase):
|
|||
'datetime': dt.datetime(2019, 6, 11),
|
||||
}
|
||||
r = """{
|
||||
"datetime": "2019-06-11 00:00:00"
|
||||
"datetime": "2019-06-11T00:00:00"
|
||||
}"""
|
||||
o = _dump(d)
|
||||
self.assertEqual(o, r)
|
||||
|
||||
def test_dump_with_decimal(self):
|
||||
def test_dump_with_set(self):
|
||||
d = {
|
||||
'decimal': Decimal('1.75'),
|
||||
'set': set([0, 1, 2, 3, 4, 5]),
|
||||
}
|
||||
r = """{
|
||||
"decimal": "1.75"
|
||||
"set": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5
|
||||
]
|
||||
}"""
|
||||
o = _dump(d)
|
||||
self.assertEqual(o, r)
|
||||
|
|
|
@ -270,7 +270,7 @@ class benedict_test_case(unittest.TestCase):
|
|||
}
|
||||
b = benedict(d)
|
||||
expected_output = """{
|
||||
"datetime": "2019-06-11 00:00:00"
|
||||
"datetime": "2019-06-11T00:00:00"
|
||||
}"""
|
||||
output = b.dump()
|
||||
self.assertEqual(output, expected_output)
|
||||
|
|
Loading…
Reference in New Issue