javascript - Python - How to export JSON in JS -
i want export json string in python js variable.
<script type="text/javascript"> var data = json.parse('{{ datajson }}'); console.log(data) </script>
if print content of datajson
get: [{"offset":0,"total":1,"units":[{"village_id":37,"village_name":"glim
but in js this: json.parse('[{"offset":0,"total":1,"units":[{"village_id":37
i use jinja2 template engine: http://jinja.pocoo.org/docs/dev/templates/#if
how can fix that?
you need mark data safe:
var data = {{ datajson|safe }};
this prevents being html-escaped. there no need use json.parse()
way; json valid javascript subset (at least insofar python json
module produces valid subset).
take account doesn't make javascript safe. may want adjust json serialisation. if using flask, tojson
filter provided ensures javascript-safe valid json:
var data = {{ data|tojson|safe }};
if not using flask, post-process json:
datajson = (json.dumps(data) .replace(u'<', u'\\u003c') .replace(u'>', u'\\u003e') .replace(u'&', u'\\u0026') .replace(u"'", u'\\u0027'))
this python code produce datajson
value can safely used in html (including attribute values) , in javascript. credit here goes flask json.htmlsafe_dumps()
function.
Comments
Post a Comment