1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import json
from decimal import Decimal
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return json.JSONEncoder.default(self, obj)
# Output has one decimal, change format if you need more
json.encoder.FLOAT_REPR = lambda o: format(o, '.1f')
# Usage:
d = Decimal("42.5")
json.dumps(d, cls=DecimalEncoder)
|
More like this
- Currency Fields with newforms by sago 6 years, 1 month ago
- ByteSplitterField by Lacour 1 year, 9 months ago
- JSON Encoder for models by bruno 4 years, 2 months ago
- parse date template tag by robhudson 3 years, 7 months ago
- format_thousands by cootetom 1 year, 11 months ago
Comments