Skip to content

Instantly share code, notes, and snippets.

@peterhel
Created October 21, 2023 18:26
Show Gist options
  • Select an option

  • Save peterhel/cf338fd26f3fdbcb36ca1675e2e0215e to your computer and use it in GitHub Desktop.

Select an option

Save peterhel/cf338fd26f3fdbcb36ca1675e2e0215e to your computer and use it in GitHub Desktop.
json.dumps(decimals)
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