Python JSON serialize a Decimal object

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

    My $.02!

    I extend a bunch of the JSON encoder since I am serializing tons of data for my web server. Here's some nice code. Note that it's easily extendable to pretty much any data format you feel like and will reproduce 3.9 as "thing": 3.9

    JSONEncoder_olddefault = json.JSONEncoder.default
    def JSONEncoder_newdefault(self, o):
        if isinstance(o, UUID): return str(o)
        if isinstance(o, datetime): return str(o)
        if isinstance(o, time.struct_time): return datetime.fromtimestamp(time.mktime(o))
        if isinstance(o, decimal.Decimal): return str(o)
        return JSONEncoder_olddefault(self, o)
    json.JSONEncoder.default = JSONEncoder_newdefault
    

    Makes my life so much easier...

提交回复
热议问题