1

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' : 'image/jpeg' })

Help would be greatly appreciated!

4
  • 2
    I'm confused. Should the value be "image/jpeg" or "image\/jpeg" ? Commented Aug 29, 2011 at 11:49
  • It's should be "image\/jpeg". I use a Javascript library that requires it to read that way. Commented Aug 29, 2011 at 12:26
  • Basically \\ is the Python version for \ as \ is part of the string syntax. I think it should work when you write 'image\\/jpeg'. Maybe you can try urllib.quote? It's useful for replacing characters in URLs, but it still might work... Commented Aug 29, 2011 at 12:44
  • 1
    I can't follow your question very well at all, I'm afraid. What exactly are you doing? Do you have some Python program generating a response to an AJAX request, or just what? Where are you "reading" the object and seeing the wrong value - in the client-side javascript? Commented Aug 29, 2011 at 15:28

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.