美文网首页
自定义json发送类和对象

自定义json发送类和对象

作者: 两分与桥 | 来源:发表于2018-06-08 09:40 被阅读42次
# json 默认不能格式化类和实例,必须自己定制
import json
from json.encoder import JSONEncoder

class JsonCustomEncoder(JSONEncoder):
    def default(self, o):
        if isinstance(o,Base): # Base 是类的名称
            return o.__dict__  # 类的 __dict__ 返回的是{'status': True, 'data': 'tiger'}
        return JSONEncoder.default(self,o)

class Base():
    def __init__(self):
        self.status = True
        self.data = 'tiger'

dic = {
    'k1': 'talent',
    'k2': Base(),
}
print(json.dumps(dic,cls=JsonCustomEncoder)  # cls 有种回调函数的意思

相关文章

网友评论

      本文标题:自定义json发送类和对象

      本文链接:https://www.haomeiwen.com/subject/eeyosftx.html