Vadorequest Vadorequest - 6 months ago 10
Javascript Question

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
I get:

But in the JS I get this:

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.