2011-04-05 117 views
3

我最近在Google App Engine中進行了大量編碼。令我驚訝的是,當使用simplejson模塊時,代碼突然出現異常。而應用程序的一個實例將打印(使用self.response.out.write(serialized)其中serialized是一本字典的字符串)JSON格式爲:單引號替換Google App Engine Web應用中的雙引號

{"error": "Your user key does not exist"} 

生產一會打印出JSON字典字符串:

{'error': 'Your user key does not exist'} 

顯然,後者是不正確的,因爲它使用單引號而不是雙引號。 (因此JSONLint或幾乎任何JSON解析時解析它)

最有趣的部分?使用logging.info('')打印到控制檯時,都會正確打印JSON。除了用於測試的打印代碼外,我幾乎在生產代碼中註釋了所有內容,問題仍然存在。

這是怎麼回事?!是否有一個魔術開關在打印到屏幕時用單引號替換所有漂亮的雙引號?


增加了對堆棧Overflowers的娛樂:

下面的代碼,在我的GAE的實例以及公共服務器也將產生JSON單引號,從而使這一最簡單的執行可能的例子。

from google.appengine.ext import webapp 
from google.appengine.ext.webapp import util 

import simplejson as json 


class MainHandler(webapp.RequestHandler): 
    def get(self): 
     testing = { "testing" : True, "why?" : 123 } 

     serialized = json.dumps(testing) 

     self.response.headers['Content-Type'] = 'application/json' 
     self.response.out.write(testing) 


def main(): 
    application = webapp.WSGIApplication([('/', MainHandler)], 
             debug=True) 
    util.run_wsgi_app(application) 


if __name__ == '__main__': 
    main() 

回答

5

現在我只是覺得啞巴。

問題是我從未將序列化代碼寫入屏幕,而是將數據數組本身寫入。因此,爲了從上面的代碼中獲得一個功能完整的例子,必須在self.response.out.write(testing)中用serialized代替testing

TL; DR:仔細檢查您的代碼以及您要打印的畫面,孩子。

+0

可以理解,因爲JSON和Python文字符號非常相似。 – 2011-04-06 01:36:05