Json中datatime问题


from datetime import datetime
from functools import singledispatch

dict = {
     "name":"小明","age":18,"height":180,'time':datetime.now()}


class MyEncoder(json.JSONEncoder):

    def default(self, o):
        try:
            return Jsondispatch.encode(o)
        except TypeError:
            return super().default(self, o)

class Jsondispatch:

    @singledispatch
    def encode(o):
        raise TypeError("Unencode type")

    @encode.register(datetime)
    def _(o):
        return '{}'.format(o.strftime('%Y-%m-%d %H:%M:%S'))



a = json.dumps(dict,cls=MyEncoder,ensure_ascii=False)
print(a)
print(type(a))
b = json.loads(a)
print(b)
print(type(b))

{
     "name": "小明", "age": 18, "height": 180, "time": "2020-05-26 00:12:37"}
<class 'str'>
{
     'name': '小明', 'age': 18, 'height': 180, 'time': '2020-05-26 00:12:37'}
<class 'dict'>
只要被singledispatch 装饰的函数,就是一个单分派的(single-dispatch )的泛函数(generic functions)。单分派:根据一个参数的类型,以不同方式执行相同的操作的行为。

你可能感兴趣的:(python)