Python JSON serialize a Decimal object

后端 未结 17 1344
星月不相逢
星月不相逢 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:10

    I tried switching from simplejson to builtin json for GAE 2.7, and had issues with the decimal. If default returned str(o) there were quotes (because _iterencode calls _iterencode on the results of default), and float(o) would remove trailing 0.

    If default returns an object of a class that inherits from float (or anything that calls repr without additional formatting) and has a custom __repr__ method, it seems to work like I want it to.

    import json
    from decimal import Decimal
    
    class fakefloat(float):
        def __init__(self, value):
            self._value = value
        def __repr__(self):
            return str(self._value)
    
    def defaultencode(o):
        if isinstance(o, Decimal):
            # Subclass float with custom repr?
            return fakefloat(o)
        raise TypeError(repr(o) + " is not JSON serializable")
    
    json.dumps([10.20, "10.20", Decimal('10.20')], default=defaultencode)
    '[10.2, "10.20", 10.20]'
    

提交回复
热议问题