File size: 666 Bytes
26e6f31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import decimal
import json
import math

from aws_lambda_powertools.shared.functions import dataclass_to_dict, is_dataclass, is_pydantic, pydantic_to_dict


class Encoder(json.JSONEncoder):
    """Custom JSON encoder to allow for serialization of Decimals, Pydantic and Dataclasses.

    It's similar to the serializer used by Lambda internally.
    """

    def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            return math.nan if obj.is_nan() else str(obj)

        if is_pydantic(obj):
            return pydantic_to_dict(obj)

        if is_dataclass(obj):
            return dataclass_to_dict(obj)

        return super().default(obj)