981377660LMT / ts

ts学习
6 stars 1 forks source link

python 如何让一个对象可序列化 #610

Open 981377660LMT opened 1 month ago

981377660LMT commented 1 month ago

https://stackoverflow.com/a/38764817

981377660LMT commented 1 month ago
import operator
from json import JSONEncoder, dumps

def _default(self, obj):
    return getattr(obj.__class__, "to_json", _default.default)(obj)

_default.default = JSONEncoder().default
JSONEncoder.default = _default

class XXX:
      def to_json(self):
         return 1
981377660LMT commented 1 month ago

monkey patch