JSON Decimal encoder

 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

  1. Currency Fields with newforms by sago 6 years, 1 month ago
  2. ByteSplitterField by Lacour 1 year, 9 months ago
  3. JSON Encoder for models by bruno 4 years, 2 months ago
  4. parse date template tag by robhudson 3 years, 7 months ago
  5. format_thousands by cootetom 1 year, 11 months ago

Comments

(Forgotten your password?)