Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 967
user Avatar asked Sep 20 '25 07:09

user


2 Answers

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);
like image 167
SMX Avatar answered Sep 22 '25 20:09

SMX


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

like image 43
Udi Avatar answered Sep 22 '25 21:09

Udi