simplejson not escaping single quote on app engine server
I'm trying to generate a properly formatted json object to use in javascript. I've tried simplejson.dumps(string), but it behaves differently on my local machine (in the python shell) vs. on the server (running google app engine). For example, locally i'll get:
>>> s= {u'hello': u"Hi, i'm here"}
>>> simplejson.dumps(s)
'{"hello": "Hi, i\'m here"}'
which all looks good.开发者_高级运维 But when i run it on the server, I get
{"hello": "Hi, i'm here"}
where the single quote is not escaped, which throws an error in my javascript.
Short of doing a secondary string.replace("'", r"\'")
, does anyone have suggestions? I'm at a loss and have already spent waay to much time trying to figure it out...
I think you are being confused by the repr
behaviour vs the actual output.
>>> s= {u'hello': u"Hi, i'm here"}
>>> simplejson.dumps(s)
'{"hello": "Hi, i\'m here"}'
>>> print simplejson.dumps(s)
{"hello": "Hi, i'm here"}
When you simply ask for the result of the simplejson call, the Python shell prints that result using repr
- which escapes it so that you can cut and paste it back in later. However, there isn't actually a backslash in the string produced by dumps
.
There's no escape needed for single quotes in JSON, and in fact there's no backslash in the string returned in your example:
>>> print simplejson.dumps(s)
{"hello": "Hi, i'm here"}
So I suspect that your javascript error is something else.
精彩评论