user
user

Reputation: 18529

Right way to escape JSON data from django template

I want to pass a dictionary from django view to a javascript file. The dictionary is built from a database populated by site users. What's the difference between these 2 methods in terms of security?

  1. var mydata = JSON.parse("{{mydata|escapejs}}");

  2. var mydata = {{ mydata|safe }};

Further, the doc at django says this for escapejs : This does not make the string safe for use in HTML. Could you show me an example of how it's unsafe & how can I make it safe.

Upvotes: 4

Views: 7342

Answers (2)

SMX
SMX

Reputation: 1442

For anyone coming across this in 2019, Django now provides a third option with the |json_script template filter. This filter takes care of properly serializing and escaping your Python object for use in HTML.

From the docs, using example data with unsafe characters my_data = {'hello': 'world</script>&amp;'}:

{{ my_data|json_script:"my-data" }}

renders to

<script id="my-data" type="application/json">
    {"hello": "world\\u003C/script\\u003E\\u0026amp;"}
</script>

You can then access this data in Javascript via

var value = JSON.parse(document.getElementById('my-data').textContent);

Upvotes: 7

Udi
Udi

Reputation: 30472

The following dictionary can break your page without proper escaping:

{'x':'</script><b>HELLO</b>'}

Inside tags, you can json.dumps it in your view and then use escapejs to stay safe.

(I believe the explanation means that if you want to show the output of json.dumps in HTML, let's say in a <pre> tag, just make sure it is escaped by not using safe or escapejs.)

Upvotes: 2

Related Questions