3

我正在尝试生成一个格式正确的 json 对象以在 javascript 中使用。我已经尝试过 simplejson.dumps(string),但它在我的本地机器(在 python shell 中)与在服务器(运行谷歌应用引擎)上的行为不同。例如,在本地我会得到:

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

这一切看起来都不错。但是当我在服务器上运行它时,我得到

{“你好”:“嗨,我在这里”}

没有转义单引号的地方,这会在我的 javascript 中引发错误。

没有做中学string.replace("'", r"\'"),有没有人有建议?我很茫然,已经花了很多时间试图弄清楚......

4

2 回答 2

2

我认为您对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

于 2010-11-05T19:55:12.663 回答
1

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

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

所以我怀疑你的javascript错误是别的。

于 2010-11-05T18:50:36.080 回答