【问题标题】:Render template to escaped string for json in Django将模板渲染为 Django 中 json 的转义字符串
【发布时间】:2013-06-07 22:43:29
【问题描述】:

这更像是一个一般的 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"&lt;span&gt;...&lt;/span&gt;"

我试过了

import json
data['unit'] = json.dumps(render_to_string('map/unit.html', context))

但这给了我"unit": ""&lt;span class=\\"unit\\"&gt;miles&lt;/span&gt;""

还有:

data['unit'] = str(render_to_string('map/unit.html', context)).replace('"','\"')

和:

data['unit'] = str(render_to_string('map/unit.html', context)).replace('"','\\"')

但都不能正确地转义双引号。

【问题讨论】:

  • 试试SafeString(render_to_string('map/unit.html', context))
  • json文件中的数据是如何存储的?
  • @alecxe 不。没用。不过,我可能已经找到了解决方案。

标签: python django django-templates escaping


【解决方案1】:

在遇到这个问题之前,我没有尝试过json.dumps。以前我只是将 python 字典转换为字符串,然后用双引号替换单引号。对于我们传递给客户端的大部分数据,它呈现了正确的 JSON 格式。现在我已经在这个问题中尝试了json.dumps,我意识到我不需要用strreplace 转换字典。我可以如下渲染脚本:

    ...
    context = { 'qs' : queryset }
    data['unit'] = render_to_string('map/unit.html', context)
    import json # I'll import this earlier
    data = json.dumps(data)
return HttpResponse(data, mimetype="application/json")

这适用于我传递给 JSON 格式的所有数据,所以效果非常好,这就是我应该一直这样做的方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 2018-10-09
    • 2011-05-16
    • 1970-01-01
    • 2019-04-29
    • 2020-10-03
    • 1970-01-01
    相关资源
    最近更新 更多