2012-02-22 17 views
3

私はjsonにsqlalchemyクエリの結果(リスト)をシリアル化しようとしています。jsonにsqlalchemyクラスをシリアライズ

これはクラスです:

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"も役に立たなかった。

私は、これは死んだ簡単なことになっているが、私はちょうど

が が実際に自動的にjsonification部品を扱うが、結果にjson.dumpsを呼び出すしようとしているボトルが私に同じエラーが発生します

この権利を取得することはできません知っています。

答えて

3

jsonに文字列を変換するのではなく、作成しようとしている辞書構造を返し、その構造からjsonを生成する独自のto_dictメソッドを定義できます。

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

私はあなたが試したことを理解していません。 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"}' 
関連する問題