Python - How to export JSON in JS

I want to export a JSON string in python into a JS variable.

<script type="text/javascript">
    var data = JSON.parse('{{ dataJSON }}');

If I print the content of dataJSON I get: [{"offset":0,"total":1,"units":[{"village_id":37,"village_name":"Glim

But in the JS I get this: JSON.parse('[{&#34;offset&#34;:0,&#34;total&#34;:1,&#34;units&#34;:[{&#34;village_id&#34;:37

I use jinja2 template engine:

How can I fix that?



You need to mark the data as safe:

var data = {{ dataJSON|safe }};

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).

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 }};

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'))

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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.