python - 将 sqlalchemy 类序列化为 json

标签 python json sqlalchemy

我正在尝试将 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"}'

关于python - 将 sqlalchemy 类序列化为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9395316/

相关文章:

java - 反序列化得到 null 字符串应该有值

python - 类型错误 : __init__() got an unexpected keyword argument error

python - SQLAlchemy 按分钟分组

python - SQLAlchemy - 创建无符号 BigInteger 的正确方法

python - 如何获得 Pandas 中每组的平均成对余弦相似度

python - MySQL Python Insert 奇怪?

javascript - 如何将 datepicker 日期转换为 JSON 对象以在 AJAX 请求中使用

python - 删除嵌套字典中隐式嵌套的重复对

python - 如何使用 numpy 创建具有 N 种颜色的离散 RGB 颜色图

android - 在 Android 中解析 JSON 的可能方法