将 sqlalchemy 类序列化为 json

发布于 2025-01-08 00:19:16 字数 1396 浏览 0 评论 0原文

我正在尝试将 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 会给我同样的错误。

I'm trying to serialize the result (a list) of an sqlalchemy query to json.

this is the class:

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))

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)

or:

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)

and I got:

TypeError(repr(o) + " is not JSON serializable")
ValueError: Single '}' encountered in format string

I tried:

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

and I got:

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

那支青花 2025-01-15 00:19:16

例如,您可以定义自己的 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"}'

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"}'
呢古 2025-01-15 00:19:16

我不确定我理解你的尝试。您不能构建 dict 并让 json. dumps() 为你做这个工作吗?

像这样的东西:

>>> class Foo:
...     id = 1
...     title = 'my title'
...     to_jsonize = ['id', 'title']
>>>
>>> dct = {name: getattr(Foo,name) for name in Foo.to_jsonize}
>>> import json
>>> json.dumps(dct)
'{"id": 1, "title": "my title"}'

I'm not sure I understand what you tried. Couldn't you build the dict and let json.dumps() do the work for you?

Something like:

>>> class Foo:
...     id = 1
...     title = 'my title'
...     to_jsonize = ['id', 'title']
>>>
>>> dct = {name: getattr(Foo,name) for name in Foo.to_jsonize}
>>> import json
>>> json.dumps(dct)
'{"id": 1, "title": "my title"}'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文