【Python】实现将对象转成字典

在编程中,常常需要把一个对象转换成一个json或是一个字典类型。在使用sqlalchemy时,定义的表对象需要把他们转换成字典类型,字典到json的格式转换就很方便了

def to_dict(dumyself):
    result = {}
    for a in dir(dumyself):

        # filter inner field by fieldname
        if a.startswith('_') or a == 'metadata':
            continue

        v = getattr(dumyself, a)

        # filter inner field by value type
        if callable(v):
            continue

        if type(v) not in (types.NoneType, types.IntType, types.LongType, types.StringType, types.UnicodeType):
            continue

        result[a] = getattr(dumyself, a)

    return result

dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。过滤掉_(下划线)开头的属性、方法,过滤掉metadata,过滤掉函数方法。使用getattr()获取对应的属性值,并写入到字典中,最终返回

Base = declarative_base()

Base.to_dict = to_dict
class Miner(Base):

    __tablename__ = 'miners_t'

    id = Column(Integer, primary_key=True)
    name = Column(String(48), nullable=False, index=True)
    ip = Column(String(20), nullable=False)  # ip
    port = Column(Integer, nullable=False)  # port
    domain_id = Column(Integer)  # domain
    location_id = Column(Integer, index=True)
    deleted = Column(Integer, nullable=False, server_default="0")
    created_at = Column(Integer, nullable=False)
    _i = Index("ip_port_idx", poolx_ip, poolx_port)

对象转字典小结:

1.过滤属性名和属性类型,得到符合要求的字段

2.获取字段对应的值

3.按照格式填充值

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值