我正在尝试使用解码JSON字符串

json.loads(request.POST.get('d'))


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

我在堆栈跟踪中收到以下错误:

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


但是如果我不在data-> 40-> html中应用span标签,它会起作用

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


这里有什么问题?

最佳答案

我想在源字符串中有反斜杠。

当我解析

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


使用json.loads(),它会失败,并显示类似的错误。

但是,当我禁用转义序列(r''字符串文字)时,它可以工作:

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


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

更新:您可以在字符串中用r'\'替换r'\\'。但是最好了解一下字符串的外观。当您在消息中插入字符串主体时,是从哪里获得的?

关于python - JSON解码字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13392162/

10-11 22:32
查看更多