2020-01-20 15:19:53 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2020-01-20 16:03:59 +00:00
|
|
|
from __future__ import absolute_import
|
|
|
|
|
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
|
|
|
|
|
|
|
|
from six import text_type
|
2020-01-20 15:19:53 +00:00
|
|
|
|
|
|
|
import json
|
|
|
|
|
|
|
|
|
|
|
|
class JSONSerializer(AbstractSerializer):
|
|
|
|
|
2020-02-20 16:14:48 +00:00
|
|
|
def __init__(self):
|
|
|
|
super(JSONSerializer, self).__init__()
|
|
|
|
|
|
|
|
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):
|
|
|
|
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):
|
|
|
|
return text_type(obj)
|
|
|
|
return text_type(obj)
|