Last active
January 16, 2025 09:06
-
-
Save felixhammerl/363e0fcc75549939b84b8c68db575640 to your computer and use it in GitHub Desktop.
Automatically cast decimals in dynamodb return values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from decimal import Decimal | |
@dataclass | |
class A: | |
x: str | |
data = { | |
'x': 'TEST', | |
} | |
result = from_dict(data_class=A, data=data, config=Config(type_hooks={Decimal: int})) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from decimal import Decimal | |
dynamodb = boto3.resource("dynamodb", region_name="...").Table(...) | |
response = dynamodb.get_item( | |
Key={ | |
"...": "...", | |
} | |
) | |
item = json.loads( | |
json.dumps(response["Item"], cls=DecimalEncoder), | |
parse_float=Decimal, | |
) | |
class DecimalEncoder(json.JSONEncoder): | |
def default(self, o): | |
if isinstance(o, Decimal): | |
return int(o) | |
return super().default(o) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment