diff --git a/benedict/serializers/json.py b/benedict/serializers/json.py index 72078fa..8cd61d4 100644 --- a/benedict/serializers/json.py +++ b/benedict/serializers/json.py @@ -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) diff --git a/tests/core/test_dump.py b/tests/core/test_dump.py index bfd18b1..7e92648 100644 --- a/tests/core/test_dump.py +++ b/tests/core/test_dump.py @@ -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) diff --git a/tests/dicts/test_benedict.py b/tests/dicts/test_benedict.py index 9ebec1c..365d8c0 100644 --- a/tests/dicts/test_benedict.py +++ b/tests/dicts/test_benedict.py @@ -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)