1

I want to know if python's json.dumps method's output is safe for rendering directly into html/js script without escaping.

my_dict = {...}
my_dict_json_str = json.dumps(my_dict)

and then rendering this

<script>
    var my_dict = {{my_dict_json_str}};
</script>

Does this work every time or are there some characters that will break it?

Martin Massera
  • 1,718
  • 1
  • 21
  • 47
  • I'd guess no, but I don't know Javascript very well. The question is, is a JSON value always a valid Javascript literal? (https://stackoverflow.com/a/3975890/1126841 shows some examples of valid literals that are not valid JSON, but nothing in the reverse direction.) – chepner Nov 28 '18 at 15:07
  • does `json.dumps` escape `/`? if not a simple `json.dumps("")` would break it. ... does `{{ }}` do additional escaping? – Roland Starke Nov 28 '18 at 15:10
  • @RolandStarke Yes; `json.dumps("")` produces `'""'` (the double quotes are part of the value). – chepner Nov 28 '18 at 15:12
  • So `/` is not escaped. in this case its not safe to output it in html context. – Roland Starke Nov 28 '18 at 15:13
  • *"rendering directly into a js file"*. That is not what you are showing. That is an html ` – charlietfl Nov 28 '18 at 15:18
  • ok I reworded that – Martin Massera Nov 28 '18 at 15:54

1 Answers1

4

json.dumps is not safe for html use without proper escaping.

>>> json.dumps({"one": "</script>"})
'{"one": "</script>"}'

This behaviour can break your html.

Martin Massera
  • 1,718
  • 1
  • 21
  • 47
g_uint
  • 1,903
  • 3
  • 17
  • 30
  • 1
    Would add that JSON *in general* is not safe for rendering as HTML. Nothing specific to python about it. – Jared Smith Nov 28 '18 at 15:42
  • so the next question is: is JSON safe for rendering as .js? and the one produced by `json.dumps` specifically? – Martin Massera Nov 28 '18 at 15:44
  • 1
    But its pretty easy to make it safe. For example for `JSON.strinfigy` in js you only need to additionally escape the following chars: `['<', '>', '/', '\u2028', '\u2029']` see the following source code: https://github.com/yahoo/serialize-javascript/blob/master/index.js#L18 I would guess in python its similar. – Roland Starke Nov 28 '18 at 15:57
  • Hi @RolandStarke thanks, please can you add this as an answer? – Martin Massera Nov 28 '18 at 22:42
  • Hi, sadly I don't know enough of python to give a confident answer. (My "world" is more php and js) – Roland Starke Nov 28 '18 at 22:50