渲染JSON而不替换Jinja中的角色 [英] Render JSON without replacing characters in Jinja

查看:94
本文介绍了渲染JSON而不替换Jinja中的角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些将被发送到JavaScript图表的Python数据。我把它转储到JSON并传递给模板。当我渲染数据时,它包含html实体(" )而不是引号,这是无效的。如何正确地将JSON数据从Python传递到JavaScript?

  pieData = [{'color':'#400068', 'name':'xyz','value':10},{'color':'#4a8624','name':'abc','value':30}] 
render_template('index.html ',piedata = json.dumps(pieData))



  var pieData2 = {{piedata}}; 
//呈现为
var pieData2 = [{" color"#34;#5461ae"" name" :" fizi.yadav" value":10},{" color"#34;#e1dce4&#34 ,#34;#34;#34;#########surya.pradhan#34;#34;值#34 ;: 30},{#34;颜色#34 :#34;#7835f0"#34; name"#34; fred.hsu#34;#34; value":276 Jinja autoescapes潜在的不安全的字符(如引号)[b] [b] [b] [/ b] [/ b] )以避免安全问题。您需要通过使用模板中的 | safe 过滤器或将其包装在 Markup 在视图中。您也可以使用 | tojson 过滤器,而不是手动解析和标记JSON。使用标记标记为安全的视图。

  from markupsafe import标记
render_template('index.html',piedata = Markup(json.dumps(pieData)))


$ b

  {{piedata | safe}} 

/ code>

最好将其转换为模板,而不要调用 json.dumps 在视图中。老版本的Flask需要调用 | tojson | safe ,但不再需要 | safe


$ b

  {{piedata | tojson}} 


I have some Python data that will be sent to a JavaScript chart. I dump it to JSON and pass it to the template. When I render the data, it contains html entities (") instead of quotes, which isn't valid. How do I correctly pass the JSON data from Python to JavaScript?

pieData = [{'color': '#400068', 'name': 'xyz', 'value': 10}, {'color': '#4a8624', 'name': 'abc', 'value': 30}]
render_template('index.html', piedata=json.dumps(pieData))

var pieData2 = {{ piedata }};
// renders as
var pieData2 = [{"color": "#5461ae", "name": "fizi.yadav", "value": 10}, {"color": "#e1dce4", "name": "surya.pradhan", "value": 30}, {"color": "#7835f0", "name": "fred.hsu", "value": 276}]

解决方案

Jinja autoescapes potentially unsafe characters (such as quotes) to avoid security issues. You need to tell it that the data you are rendering is safe, either by using the |safe filter in the template or wrapping it in Markup in the view. You can also use the |tojson filter rather than parsing and marking the JSON manually.

Use Markup to mark it safe from the view.

from markupsafe import Markup
render_template('index.html', piedata=Markup(json.dumps(pieData)))

Or mark it safe in the template.

{{ piedata|safe }}

Preferably, just convert it in the template without calling json.dumps in the view. Older versions of Flask required calling |tojson|safe, but the |safe is no longer needed.

{{ piedata|tojson }}

这篇关于渲染JSON而不替换Jinja中的角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆