Skip to content Skip to sidebar Skip to footer

Python - How To Export JSON In JS

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

Solution 1:

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.


Post a Comment for "Python - How To Export JSON In JS"