I am trying to decode a JSON string using
json.loads(request.POST.get('d'))
where d is a POST parameter containing a JSON string.
I get the following error in the stacktrace:
ValueError: Unterminated string starting at: line 1 column 22 (char 22)
This is the JSON string:
{"data":{"40":{"html":"<span style=\"color:#ffffff;\">test</span>","background":"transparent"},"41":{"html":"","background":"transparent"},"42":{"html":"","background":"transparent"}},"action":"save"}
However it works if I dont apply the span tag in data->40->html
{"data":{"40":{"html":"test","background":"transparent"},"41":{"html":"","background":"transparent"},"42":{"html":"","background":"transparent"}},"action":"save"}
What is the problem here?
3 Answers 3
I suppose there is something with backslashes in the source string.
When I parse
"""{"data":{"40":{"html":"<span style=\"color:#ffffff;\">test</span>","background":"transparent"},"41":{"html":"","background":"transparent"},"42":{"html":"","background":"transparent"}},"action":"save"}"""
with json.loads(), it fails with a similar error.
However, when I disable escape sequences (r'' string literal), it works:
r"""{"data":{"40":{"html":"<span style=\"color:#ffffff;\">test</span>","background":"transparent"},"41":{"html":"","background":"transparent"},"42":{"html":"","background":"transparent"}},"action":"save"}"""
Obviously, '\"' in your string is being escaped and results in '"' when you construct the string, probably in JS(?). Haven't seen the code that builds it, but try adding an extra backslash: '\\"'
UPDATE: You may replace r'\' with r'\\' in a string. But it is better to understand how does the string look to begin with. When you inserted the string body into your message, where did you get it from?
6 Comments
How do you know that is the string you're getting? It works for me:
>>> 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'}}}
Notice that I used a raw string for ss because otherwise \" will just be replaced by " in the string resulting in '"<span style="color:#ffffff;">test</span>"' which doesn't work for obvious reasons.
4 Comments
r: r"this is a raw string". "this is not a raw string". This doesn't work with "variables" if that's what your asking though: foo = "bar"; rbar #doesn't make bar a raw stringThis worked for us:
json.loads(request.POST.get('d').encode('string-escape'))
request.POST.get('d'))?