forked from aws-powertools/powertools-lambda-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_encoder.py
More file actions
26 lines (18 loc) · 697 Bytes
/
json_encoder.py
File metadata and controls
26 lines (18 loc) · 697 Bytes
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
26
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):
if obj.is_nan():
return math.nan
return str(obj)
if is_pydantic(obj):
return pydantic_to_dict(obj)
if is_dataclass(obj):
return dataclass_to_dict(obj)
return super().default(obj)