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)。單分派:根據一個參數的類型,以不同方式執行相同的操作的行爲。