2022-10-14 14:53:06 +00:00
|
|
|
import json
|
|
|
|
|
2023-03-09 10:29:36 +00:00
|
|
|
# fix benedict json dumps support - #57 #59 #61
|
|
|
|
from json import encoder
|
|
|
|
|
2020-01-20 15:19:53 +00:00
|
|
|
from benedict.serializers.abstract import AbstractSerializer
|
2020-02-19 17:12:36 +00:00
|
|
|
from benedict.utils import type_util
|
|
|
|
|
2020-01-20 15:19:53 +00:00
|
|
|
|
|
|
|
class JSONSerializer(AbstractSerializer):
|
2022-02-13 10:56:44 +00:00
|
|
|
"""
|
|
|
|
This class describes a json serializer.
|
|
|
|
"""
|
|
|
|
|
2023-03-09 10:29:36 +00:00
|
|
|
@staticmethod
|
|
|
|
def disable_c_make_encoder():
|
|
|
|
encoder.c_make_encoder = None
|
|
|
|
|
2020-02-20 16:14:48 +00:00
|
|
|
def __init__(self):
|
2022-12-31 17:33:20 +00:00
|
|
|
super().__init__(
|
2022-10-05 14:43:46 +00:00
|
|
|
extensions=[
|
|
|
|
"json",
|
|
|
|
],
|
|
|
|
)
|
2020-02-20 16:14:48 +00:00
|
|
|
|
|
|
|
def decode(self, s, **kwargs):
|
2020-01-20 15:19:53 +00:00
|
|
|
data = json.loads(s, **kwargs)
|
|
|
|
return data
|
|
|
|
|
2020-02-20 16:14:48 +00:00
|
|
|
def encode(self, d, **kwargs):
|
2022-02-13 10:35:43 +00:00
|
|
|
kwargs.setdefault("default", self._encode_default)
|
2020-01-20 15:19:53 +00:00
|
|
|
data = json.dumps(d, **kwargs)
|
|
|
|
return data
|
2020-02-19 17:12:36 +00:00
|
|
|
|
2020-02-20 16:14:48 +00:00
|
|
|
def _encode_default(self, obj):
|
|
|
|
if type_util.is_set(obj):
|
2020-02-19 17:12:36 +00:00
|
|
|
return list(obj)
|
|
|
|
elif type_util.is_datetime(obj):
|
|
|
|
return obj.isoformat()
|
|
|
|
elif type_util.is_decimal(obj):
|
2022-02-17 22:54:30 +00:00
|
|
|
return str(obj)
|
|
|
|
return str(obj)
|