这更像是一个一般的 python 问题,但在 Django 的上下文中它变得有点复杂。
我有一个模板,像这样,简化:
<span class="unit">miles</span>
我正在用 jquery 和 ajax 替换一个元素:
$.getJSON('/getunit/', function(data){
$('#unitHolder').html(data.unit_html);
});
它转到一个视图函数来检索 json 数据(比这个模板更多的数据)。所以我想把它作为 json 来提供,而不仅仅是一个字符串。所以,相关的代码是这样的:
...
context = { 'qs' : queryset }
data['unit'] = render_to_string('map/unit.html', context)
data = str(data).replace('\'','"') #json wants double quotes
return HttpResponse(data, mimetype="application/json")
这适用于我们所有的其他数据,但不适用于模板,因为它有双引号,没有转义。我的问题是,如何在 python 中转义一个字符串以用于 json 格式?请注意,render_to_string() 以 unicode 呈现字符串,因此u"<span>...</span>"
.
我试过了
import json
data['unit'] = json.dumps(render_to_string('map/unit.html', context))
但这给了我"unit": ""<span class=\\"unit\\">miles</span>""
。
还:
data['unit'] = str(render_to_string('map/unit.html', context)).replace('"','\"')
和:
data['unit'] = str(render_to_string('map/unit.html', context)).replace('"','\\"')
但两者都不能正确地转义双引号。