Python JSON serialize a Decimal object

后端 未结 17 1448
星月不相逢
星月不相逢 2020-11-22 08:27

I have a Decimal(\'3.9\') as part of an object, and wish to encode this to a JSON string which should look like {\'x\': 3.9}. I don\'t care about p

17条回答
  •  生来不讨喜
    2020-11-22 09:27

    How about subclassing json.JSONEncoder?

    class DecimalEncoder(json.JSONEncoder):
        def default(self, o):
            if isinstance(o, decimal.Decimal):
                # wanted a simple yield str(o) in the next line,
                # but that would mean a yield on the line with super(...),
                # which wouldn't work (see my comment below), so...
                return (str(o) for o in [o])
            return super(DecimalEncoder, self).default(o)
    

    Then use it like so:

    json.dumps({'x': decimal.Decimal('5.5')}, cls=DecimalEncoder)
    

提交回复
热议问题