python 数据库查询序列化_python-将sqlalchemy类序列化为json

我正在尝试将sqlalchemy查询的结果(列表)序列化为json.

这是课程:

class Wikilink(Base):

__tablename__='Wikilinks'

__table_args__={'extend_existing':True}

id = Column(Integer,autoincrement=True,primary_key=True)

title = Column(Unicode(350))

user_ip = Column(String(50))

page = Column(String(20))

revision = Column(String(20))

timestamp = Column(String(50))

我想我的问题是__repr __(self):函数.

我尝试了类似的东西:

return '{{0}:{"title":{1}, "Ip":{2}, "page":{3} ,"revision":{4}}}'.format(self.id,self.title.encode('utf-8'),self.user_ip,self.page,self.revision)

要么:

return '{"id"={0}, "title"={1}, "Ip"={2}}'.format(self.id,self.title.encode('utf-8'),self.user_ip.encode('utf-8'),self.page,self.revision)

我得到:

TypeError(repr(o) + " is not JSON serializable")

ValueError: Single '}' encountered in format string

我试过了:

return '{id=%d, title=%s, Ip=%s}'%(self.id,self.title.encode('utf-8'),self.user_ip.encode('utf-8'))

我得到:

TypeError: {id=8126, title=1 בדצמבר, Ip=147.237.70.106} is not JSON serializable

像这样(根据JSON格式)在周围添加“”:“ id” =“%d”,“ title” =“%s”,“ Ip” =“%s”也不起作用.

我知道这简直太简单了,但是我做对了

实际上bottle是自动处理jsonification部分,但是尝试在结果上调用json.dumps会给我同样的错误.

解决方法:

您可以定义自己的to_dict方法,而不是尝试将字符串转换为json,该方法返回似乎要尝试创建的字典结构,然后从该结构生成json:

>>> import json

>>> d = {'id':8126, 'title':u'1 בדצמבר', 'ip':'147.237.70.106'}

>>> json.dumps(d)

'{"ip": "147.237.70.106", "id": 8126, "title": "1 \\u05d1\\u05d3\\u05e6\\u05de\\u05d1\\u05e8"}'

标签:sqlalchemy,json,python

来源: https://codeday.me/bug/20191101/1985295.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值