django - exception handling on JSON encoding format

This is an exception of the encoding format, because in the docking of the crawler meta service, when sending data through http, the packaged data package is not in the correct format

string={'domain': 'android.myapp.com', 'url': 'https://android.myapp.com/myapp/searchAjax.htm?kw=MM%E5%BA%94%E7%94%A8%E5%95%86%E5%9C%BA&pns=&sid='}

Because there is no single quotation mark, only double quotation mark in JSON, we need to replace single quotation mark with double quotation mark

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes

There are many ways, such as regular

data = re.sub('\'', '\"', string.decode("utf-8"))

It can also be processed with simple string

string.replace('\"', '\'')

Here is the exception throw of the system

Traceback (most recent call last):
  File "/home/yerikyu/spidermax/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/yerikyu/spidermax/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/yerikyu/spidermax/lib/python3.5/site-packages/django/core/handlers/base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/yerikyu/spidermax/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/yerikyu/spidermax/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/yerikyu/SG/spidermax/spider/views.py", line 43, in post
    data = json.loads(request.body.decode("utf-8"))
  File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Tags: Python JSON Django Android encoding

Posted on Mon, 02 Dec 2019 20:02:16 -0800 by Mythic Fr0st