alonisser
alonisser

Reputation: 12068

serializing sqlalchemy class to json

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.

Upvotes: 3

Views: 2743

Answers (2)

jcollado
jcollado

Reputation: 40374

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"}'

Upvotes: 3

Rik Poggi
Rik Poggi

Reputation: 29302

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"}'

Upvotes: 1

Related Questions