Created
October 21, 2023 18:26
-
-
Save peterhel/cf338fd26f3fdbcb36ca1675e2e0215e to your computer and use it in GitHub Desktop.
json.dumps(decimals)
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
| import json | |
| import decimal | |
| class ComplexEncoder(json.JSONEncoder): | |
| def default(self, obj): | |
| if isinstance(obj, decimal.Decimal): | |
| return int(obj) if obj % 1 == 0 else float(obj) | |
| return json.JSONEncoder.default(self, obj) | |
| data_with_decimals = { | |
| "value": decimal.Decimal(3.14) | |
| } | |
| print(json.dumps(data_with_decimals, cls=ComplexEncoder)) | |
| # {"value": 3.14} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment