I’ve got an interesting problem with JSON and Django. I think I’ve narrowed it down to this problem. The problem is that I have a JSON object something like this:
{"embed": "<iframe width='640' height='360' src='http://www.youtube.com/embed/Sw5Gk1L4LQE?wmode=opaque' frameborder='0' allowfullscreen></iframe>"}
In PDB if I print out this as a simplejson.dumps I get this (notice the double quotes):
{"embed": "<iframe width=\\"640\\" height=\\"360\\" src=\\"http://www.youtube.com/embed/Sw5Gk1L4LQE?wmode=opaque\\" frameborder=\\"0\\" allowfullscreen></iframe>"}
The actual HttpResponse object has removed one slash from every set of double escapes like this.
return HttpResponse(simplejson.dumps(result), 'application/json'
{"embed": "<iframe width=\"640\" height=\"360\" src=\"http://www.youtube.com/embed/Sw5Gk1L4LQE?wmode=opaque\" frameborder=\"0\" allowfullscreen></iframe>"}
On the client I am using jQuery’s parseJSON and I am having problems with the one that has single escaped characters (3rd one) as it doesn’t see them as escaped. But it is actual valid JSON where as the 2nd one works when I try parseJSON on it directly in the console but it is not in fact valid JSON (according to JSONLint.com).
Any ideas of what I can do to get this JSON object from Django to the client and have the embed code intact? I’m hoping that is a small oversite on my part.
Ok so an hour later I finally realized I had made several small mistakes on this that made most everything break. I was loading the page locally instead of serving it through Django (just so I could test the jQuery Mobile stuff I was doing).
In that local file I was copy/paste in the output from the JSON view in Django.
I tried to use a JSONP call to that view and because of the jQuery JSONCallback it was throwing errors.
In the end the correct way for testing this was to serve the HTML through Django so that I didn’t have to use JSONP and when I did that parseJSON accepted the JSON that had single escaped double quotes \” where as it supposedly won’t accept from copying and pasting in since that isn’t a response object.
Hopefully my mistakes will help someone else out in the future.