simplejson 不会在应用程序引擎服务器上转义单引号
我正在尝试生成一个格式正确的 json 对象以在 javascript 中使用。我尝试过 simplejson.dumps(string),但它在我的本地计算机(在 python shell 中)与在服务器上(运行 google 应用引擎)的行为不同。例如,在本地我会得到:
>>> s= {u'hello': u"Hi, i'm here"}
>>> simplejson.dumps(s)
'{"hello": "Hi, i\'m here"}'
看起来都不错。但是当我在服务器上运行它时,我得到
{"hello": "Hi, i'm here"} ,
其中单引号没有转义,这会在我的 javascript 中引发错误。
缺少二次 string.replace("'", r"\'")
,有人有建议吗?我很茫然,已经花了很多时间试图弄清楚......
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JSON 中的单引号不需要转义,事实上,您的示例中返回的字符串中没有反斜杠:
所以我怀疑您的 javascript 错误是其他的。
There's no escape needed for single quotes in JSON, and in fact there's no backslash in the string returned in your example:
So I suspect that your javascript error is something else.
我认为您对
repr
行为与实际输出感到困惑。当您只是询问 simplejson 调用的结果时,Python shell 会使用
repr
打印该结果 - 它会将其转义,以便您稍后可以将其剪切并粘贴回来。然而,dumps
生成的字符串中实际上并没有反斜杠。I think you are being confused by the
repr
behaviour vs the actual output.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 bydumps
.