开发者

How do I deserialise (deserialize) HTML fragments in JSON from simplejson.dumps?

开发者 https://www.devze.com 2023-03-29 01:06 出处:网络
I\'m working on a Django project where one of the front end guys has asked that, for one of our ajax request, he would like me to return a JSON dict, with one of the keys being some rendered HTML from

I'm working on a Django project where one of the front end guys has asked that, for one of our ajax request, he would like me to return a JSON dict, with one of the keys being some rendered HTML from a template. So, eg:

d = {
  "hits": 22,
  "page": 3,
  "somehhtml": """<div id='item1'>Something</div><div i开发者_C百科d='item2'>More Stuff</div>

<p>More after some linebreaks.</p>"""
}

When I use simplejson.dumps to return this, it's escaping the HTML, presumably to make it valid JSON, with loads of \n linebreak characters, and quote chars escaped.

As a hack I've got it working by adding a string template replacement char to the dict before serialising it with dumps(), and then replacing it with the rendered template before sending it back to the browser. This, obviously, is horrible, and surely can't be the correct way to do it.

So, is the correct way to handle this to use some jQuery/JS way of deserialising on the client, or do I need to write my own serialiser at the Python end to not escape certain things? I tried passing it to eval() in JS, but that gives me a SyntaxError.

Are there practical reasons why what I'm currently doing (ie, not escaping the chars) is a bad idea? (To help me explain, not because I don't think I should change it).

Thanks!

Ludo.


I don't understand why you need to unescape your json string, while it should be escaped to be a valid javascript and python string ?

And by the way the newlines \n don't have nothing to do with json dumper is just because the value of the key "somehhtml" is a multiline string that contain new lines (which i think is a mistake maybe you wanted to put <br />).

For summary let's put some code :) :

python

>>> import json
>>> json.dumps(d)
'{"hits": 22, "page": 3, "somehhtml": "<div id=\'item1\'>Something</div><div id=\'item2\'>More Stuff</div>\\n\\n<p>More after some linebreaks.</p>"}'

javascript

>>> s = '{"hits": 22, "page": 3, "somehhtml": "<div id=\'item1\'>Something</div><div id=\'item2\'>More Stuff</div>\\n\\n<p>More after some linebreaks.</p>"}'
>>> JSON.parse(s)
Object { hits=22, page=3, somehhtml="<div id='item1'>Somethi...er some linebreaks.</p>"}
// eval is not safe, but you should add a parentheses as a workaround  
>>> eval('(' + s + ')')
Object { hits=22, page=3, somehhtml="<div id='item1'>Somethi...er some linebreaks.</p>"}
0

精彩评论

暂无评论...
验证码 换一张
取 消