JSON解码字符串

时间:2012-11-15 05:46:01

标签: python json python-2.7

我正在尝试使用

解码JSON字符串
json.loads(request.POST.get('d'))

其中d是包含JSON字符串的POST参数。

我在stacktrace中收到以下错误:

ValueError: Unterminated string starting at: line 1 column 22 (char 22)

这是JSON字符串:

{"data":{"40":{"html":"<span style=\"color:#ffffff;\">test</span>","background":"transparent"},"41":{"html":"","background":"transparent"},"42":{"html":"","background":"transparent"}},"action":"save"}

然而,如果我不在数据中使用span标签,那么它可以工作 - &gt; 40-&gt; html

{"data":{"40":{"html":"test","background":"transparent"},"41":{"html":"","background":"transparent"},"42":{"html":"","background":"transparent"}},"action":"save"}

这里有什么问题?

3 个答案:

答案 0 :(得分:1)

我想源代码字符串中有一些反斜杠。

解析时

"""{"data":{"40":{"html":"<span style=\"color:#ffffff;\">test</span>","background":"transparent"},"41":{"html":"","background":"transparent"},"42":{"html":"","background":"transparent"}},"action":"save"}""" 

使用json.loads(),它失败并出现类似的错误。

但是,当我禁用转义序列(r&#39;&#39;字符串文字)时,它可以正常工作:

r"""{"data":{"40":{"html":"<span style=\"color:#ffffff;\">test</span>","background":"transparent"},"41":{"html":"","background":"transparent"},"42":{"html":"","background":"transparent"}},"action":"save"}"""

显然,在构造字符串时,字符串中的'\"'被转义并导致'"',可能是在JS(?)中。 Haven没有看到构建它的代码,但尝试添加额外的反斜杠:'\\"'

更新:您可以在字符串中将r'\'替换为r'\\'。但是最好先了解字符串的外观。当您将字符串正文插入到邮件中时,您从哪里获取它?

答案 1 :(得分:0)

你怎么知道这是你得到的字符串?它对我有用:

>>> ss = r'{"data":{"40":{"html":"<span style=\"color:#ffffff;\">test</span>","background":"transparent"},"41":{"html":"","background":"transparent"},"42":{"html":"","background":"transparent"}},"action":"save"}'
>>> json.loads(ss)
{u'action': u'save', u'data': {u'42': {u'html': u'', u'background': u'transparent'}, u'40': {u'html': u'<span style="color:#ffffff;">test</span>', u'background': u'transparent'}, u'41': {u'html': u'', u'background': u'transparent'}}}

请注意,我使用了ss的原始字符串,否则\"将被字符串中的"替换,从而导致'"<span style="color:#ffffff;">test</span>"'无效的原因。

答案 2 :(得分:0)

这对我们有用:

json.loads(request.POST.get('d').encode('string-escape'))
相关问题