Django escapejs and simplejson

I am trying to encode a Python array in json using simplejson.dumps:

In [30]: s1 = ['test', '<script>'] In [31]: simplejson.dumps(s1) Out[31]: '["test", "<script>"]' 

It works great.

But first, I want to avoid the lines (using escapejs from Django) before calling simplejson.dumps:

 In [35]: s_esc Out[35]: [u'test', u'\\u003Cscript\\u003E'] In [36]: print simplejson.dumps(s_esc) ["test", "\\u003Cscript\\u003E"] 

My problem: I want the escaped string to be: ["test", "\u003Cscript\u003E"] instead of ["test", "\\u003Cscript\\u003E"]

I can use replace :

 In [37]: print simplejson.dumps(s_esc).replace('\\\\', '\\') ["test", "\u003Cscript\u003E"] 

But is this a good approach? I just want to avoid strings before their json encoding. Therefore, when I use them in the template, there will be no syntax errors.

Thanks.:)

+6
source share
2 answers

simplejson 2.1.0 and later include a JSONEncoderForHTML encoder that does exactly what you want. To use it in your example:

 >>> s1 = ['test', '<script>'] >>> simplejson.dumps(s1, cls=simplejson.encoder.JSONEncoderForHTML) '["test", "\\u003cscript\\u003e"]' 

I came across this recently when I did not have control over the code that generated the data structures, so I could not avoid the rows when they were being collected. JSONEncoderForHTML solved the problem neatly at the output point.

Of course you need to have simplejson 2.1.0 or later. (Django used to come with an older version, and Django 1.5 did not fully recognize django.utils.simplejson.) If for some reason you cannot update, the JSONEncoderForHTML code is relatively small and can probably be ported to earlier code or used with Python 2.6+ json package - although I don't know, I tried this myself.

+8
source

You are performing operations in the wrong order. You should dump your data into a JSON string and then avoid that string. You can perform escaping using the addslashes Django filter.

0
source

Source: https://habr.com/ru/post/899396/


All Articles