1

I have a textarea within a form on a webpage that has "HTML" content.

<!-- HTML -->
<textarea id="my-textarea">
    <div class="this">Content here &amp; here!</div>
</textarea>

I fetch the content with Javascript and use encodeURIComponent to safely encode the string for AJAX JSON. and store it into a key/value array. (python dict)

// Javascript
var textarea = document.getElementById('my-textarea').value;
var data = {};
data['html'] = encodeURIComponent(textarea);
console.log(data);
// prints --> {html: "%3Cdiv%20class%3D%22this%22%3EContent%20here%20%26amp%3B%20here%3C%2Fdiv%3E"}

// In AJAX function.
var json = "data=" + JSON.stringify(data);

I then send the data to Django class based view and in post I have

# Python / Django
if request.is_ajax():
    print(request.POST)
    # prints --> <QueryDict: {'data': ['{"code":"<div class="this">Content here &amp; here</div>"}']}>

    data = request.POST.get('data', None)
    if data:
        data = json.loads(data)

This throws an error as below:

Traceback (most recent call last):
  File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/tr/dev/host-root/apps/trenddjango2/django/common/views/dashboard/mixins.py", line 56, in dispatch
    return super(TemplateDashboardMixin, self).dispatch(request, *args, **kwargs)
  File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/tr/dev/host-root/apps/trenddjango2/django/common/views/dashboard/catalogue.py", line 550, in post
    data = json.loads(jsonData)
  File "/usr/local/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python3.8/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 22 (char 21)

I have found if I remove the "" double quotes within class="this", the string will load correctly.

My question is: How do I load a JSON string with double quotes in python even with it being escaped as %22 ?

1 Answer 1

0

Use \\ to escape it.

json.loads('{"code":"<div class=\\"this\\">Content here &amp; here</div>"}')

this will work as you expected. The example below shows you how to escape.

'<div class="this">Content here &amp; here!</div>'.replace(/"/g, '\\\\"')

Result is:

"<div class=\\"this\\">Content here &amp; here!</div>"
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to escape "Double Quotes" in javascript so that Django receives the escaped string?
@DavidTovmasyan That worked for double quotes, but now Python throws error with the ampersand character. Is there a way to make a string purely JSON friendly between Javascript and Python? Or do I need to escape characters as they arise, what are those characters that need escaping and how would an ampersand be escaped? I used encodeURIComponent(textarea.replace(/"/g, '\\\\"')) which doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.