Python JSON serialize a Decimal object

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

    You can create a custom JSON encoder as per your requirement.

    import json
    from datetime import datetime, date
    from time import time, struct_time, mktime
    import decimal
    
    class CustomJSONEncoder(json.JSONEncoder):
        def default(self, o):
            if isinstance(o, datetime):
                return str(o)
            if isinstance(o, date):
                return str(o)
            if isinstance(o, decimal.Decimal):
                return float(o)
            if isinstance(o, struct_time):
                return datetime.fromtimestamp(mktime(o))
            # Any other serializer if needed
            return super(CustomJSONEncoder, self).default(o)
    

    The Decoder can be called like this,

    import json
    from decimal import Decimal
    json.dumps({'x': Decimal('3.9')}, cls=CustomJSONEncoder)
    

    and the output will be:

    >>'{"x": 3.9}'
    

提交回复
热议问题