2011-03-23 78 views
-2

可能重複:
How to JSON encode Entities?如何JSON編碼?

我開始使用谷歌應用程序引擎。我想讓Twitter這樣的AJAX聊天。

class ChatMessage(db.Model): 
    message = db.StringProperty() 
    created = db.DateTimeProperty(auto_now=True) 

服務器JSON編碼的響應,

class RPCHandler(webapp.RequestHandler): 
    def get(self): 
    chat_list = {'message':'Hello!'} 
    self.response.out.write(simplejson.dumps(chat_list)) 

結果:你好!

這沒關係。但替換RPCHandler

class RPCHandler(webapp.RequestHandler): 
    def get(self): 
    newchat = ChatMessage(message="Hi!") 
    newchat.put() 
    que = db.Query(ChatMessage).order('-created') 
    chat_list = que.fetch(limit=1) 

    self.response.out.write(simplejson.dumps(chat_list)) 

結果:錯誤。服務器不可訪問(獲取)

如何JSON編碼數據庫中的數據?

+0

這是一個dup http://stackoverflow.com/questions/5397793/how-to-json-encode-entities – Calvin 2011-03-23 07:01:16

回答

0

Python有一個稱爲json可自動序列化和反序列化字典模塊,列表和其他本地Python對象(如果您提供了接口,則爲複雜類型)。

如果你能回到你的數據庫查詢作爲詞典的結果,那麼你可以簡單地使用:

import json 
as_json = json.dumps(dictionary) 

更多參考,請訪問官方json module documentatioñ。