I have been coding extensively in Google App Engine recently. To my surprise, when using the simplejson module, the code started suddenly behaving weirdly. While one instance of the app will print (using self.response.out.write(serialized)
where serialized
is a dictionary string) JSON formatted as:
{"error": "Your user key does not exist"}
the production one will print out the JSON dictionary string as:
{'error': 'Your user key does not exist'}
Obviously, the latter one is incorrect, as it uses single quotes, instead of double quotes. (and thus JSONLint or pretty much any JSON parses dies when parsing it)
Funniest part? When printed to console using logging.info('')
both print the JSON correctly. I commented out pretty much everything in the production code except for the printing code for testing and the problem remains.
What is going on?! Is there a magic switch somewhere that replaces all the nice double quotes with single quotes when printed to the screen?!
Added for the entertainment of Stack Overflowers:
The code below, executed on my instance of GAE as well as the public server will also produce JSON with single quotes, thus making this the simplest example possible.
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()
And now I just feel dumb.
The problem was that I never wrote the serialized code to the screen, but rather the data array itself. Thus, to get a fully functional example from the code above, one has to replace testing
with serialized
in the self.response.out.write(testing)
.
TL;DR: Double check your code and what you are printing to screen, kids.
精彩评论