simplejson 不会在应用程序引擎服务器上转义单引号

发布于 2024-10-01 08:33:22 字数 472 浏览 0 评论 0原文

我正在尝试生成一个格式正确的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

金橙橙 2024-10-08 08:33:23

JSON 中的单引号不需要转义,事实上,您的示例中返回的字符串中没有反斜杠:

>>> print simplejson.dumps(s)
{"hello": "Hi, i'm here"}

所以我怀疑您的 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:

>>> print simplejson.dumps(s)
{"hello": "Hi, i'm here"}

So I suspect that your javascript error is something else.

甜`诱少女 2024-10-08 08:33:22

我认为您对 repr 行为与实际输出感到困惑。

>>> 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"}

当您只是询问 simplejson 调用的结果时,Python shell 会使用 repr 打印该结果 - 它会将其转义,以便您稍后可以将其剪切并粘贴回来。然而,dumps 生成的字符串中实际上并没有反斜杠。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文