2012-02-22 2 views
3

json에 대한 sqlalchemy 쿼리의 결과 (목록)를 직렬화하려고합니다. sqlalchemy 클래스를 json으로 serialize

은 클래스입니다 :

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으로 변환하는 대신 자신이 작성하려고하는 사전 구조를 반환하는 사용자 고유의 to_dict 메소드를 정의한 다음 해당 구조에서 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"}' 
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"}' 
관련 문제