JSONSerializer._encode_default()   A
last analyzed

Complexity

Conditions 4

Size

Total Lines 8
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 4
nop 2
1
import json
2
3
from benedict.serializers.abstract import AbstractSerializer
4
from benedict.utils import type_util
5
6
7
class JSONSerializer(AbstractSerializer):
8
    """
9
    This class describes a json serializer.
10
    """
11
12
    def __init__(self):
13
        super().__init__(
14
            extensions=[
15
                "json",
16
            ],
17
        )
18
19
    def decode(self, s, **kwargs):
20
        data = json.loads(s, **kwargs)
21
        return data
22
23
    def encode(self, d, **kwargs):
24
        kwargs.setdefault("default", self._encode_default)
25
        data = json.dumps(d, **kwargs)
26
        return data
27
28
    def _encode_default(self, obj):
29
        if type_util.is_set(obj):
30
            return list(obj)
31
        elif type_util.is_datetime(obj):
32
            return obj.isoformat()
33
        elif type_util.is_decimal(obj):
34
            return str(obj)
35
        return str(obj)
36