Python AJAX response string literal
I have an AJAX response that returns a JSON object. One of the dictionary values is supposed to read:
"image\/jpeg"
But instead in reads:
"images\\/jpeg"
I've gone through the documentation on string literals and how to ignore escape sequences, and I've tried to prefix the string with 'r', but so far no luck.
My JSON encoded dictionary looks like this:
response.append({ 'name' : i.pk, 'size' : False, 'type' : 'ima开发者_JAVA技巧ge/jpeg' })
Help would be greatly appreciated!
According to the JSON spec, the \
character should be escaped as \\
in JSON.
So the Python json library is correct:
>>> import json
>>> json.dumps({"type": r"image\/jpeg", "size": False})
'{"type": "image\\\\/jpeg", "size": false}'
When the JSON is parsed/evaluated in the browser, the type
attribute will have the correct value image\/jpeg
.
The Python JSON parser of course handles the escaping as well:
>>> print(json.loads(json.dumps({"type": r"image\/jpeg", "size": False}))["type"])
image\/jpeg
I find it very strange that your javascript library requires that particular value for a value that looks like it is used to identify a resource's mime type.
精彩评论