Python-如何在JS中导出JSON [英] Python - How to export JSON in JS
问题描述
我想将python中的JSON字符串导出到JS变量中.
I want to export a JSON string in python into a JS variable.
<script type="text/javascript">
var data = JSON.parse('{{ dataJSON }}');
console.log(data)
</script>
如果我打印dataJSON
的内容,则会得到:[{"offset":0,"total":1,"units":[{"village_id":37,"village_name":"Glim
If I print the content of dataJSON
I get: [{"offset":0,"total":1,"units":[{"village_id":37,"village_name":"Glim
但是在JS中,我得到了这个:JSON.parse('[{"offset":0,"total":1,"units":[{"village_id":37
But in the JS I get this: JSON.parse('[{"offset":0,"total":1,"units":[{"village_id":37
我使用jinja2模板引擎: http://jinja.pocoo.org/docs /dev/templates/#if
I use jinja2 template engine: http://jinja.pocoo.org/docs/dev/templates/#if
我该如何解决?
推荐答案
您需要将数据标记为安全:
You need to mark the data as safe:
var data = {{ dataJSON|safe }};
这可以防止将其转义为HTML.无需以这种方式使用JSON.parse()
. JSON是有效的JavaScript子集(至少在Python json
模块生成有效子集的范围内).
This prevents it from being HTML-escaped. There is no need to use JSON.parse()
this way; JSON is a valid JavaScript subset (at least insofar that the Python json
module produces a valid subset).
请注意,这不会使其成为 JavaScript安全.您可能要调整JSON序列化.如果您使用的是Flask,则会提供tojson
过滤器,以确保您获取JavaScript安全的有效JSON:
Take into account that this doesn't make it JavaScript safe. You may want to adjust your JSON serialisation. If you are using Flask, a tojson
filter is provided that ensures you get JavaScript-safe valid JSON:
var data = {{ data|tojson|safe }};
如果您不使用Flask,请对JSON进行后处理:
If you are not using Flask, post-process the JSON:
dataJSON = (json.dumps(data)
.replace(u'<', u'\\u003c')
.replace(u'>', u'\\u003e')
.replace(u'&', u'\\u0026')
.replace(u"'", u'\\u0027'))
这是生成dataJSON
值的Python代码,该值可以在HTML(包括属性值)和JavaScript中安全使用.这里要感谢 Flask json.htmlsafe_dumps()
函数.
This is Python code to produce a dataJSON
value that can be safely used in HTML (including attribute values) and in JavaScript. Credit here goes to the Flask json.htmlsafe_dumps()
function.
这篇关于Python-如何在JS中导出JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!