将sqlalchemy类序列化为json [英] serializing sqlalchemy class to json

查看:153
本文介绍了将sqlalchemy类序列化为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to serialize the result (a list) of an sqlalchemy query to 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):函数上. 我尝试过类似的事情:

and I guess my problem is with the __repr__(self): function. I tried something like:

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"也不起作用.

adding "" around (according to the JSON formatting) like this: "id"="%d", "title"="%s", "Ip"="%s" didn't help either.

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

I know this is supposed to be dead simple but I just can't get this right

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

actually bottle is handling the jsonification part automatically, but trying to call json.dumps on the result gives me the same errors.

推荐答案

例如,您可以定义自己的to_dict方法,该方法返回看起来像您的字典结构,而不是尝试将字符串转换为json.尝试创建,然后从该结构生成json:

Instead of trying to convert to json a string, you could define, for example, your own to_dict method that returns the dictionary structure it seems you're trying to create and, after that, generate the json from that structure:

>>> 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆