django-关于JSON编码格式的异常处理

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django-关于JSON编码格式的异常处理相关的知识,希望对你有一定的参考价值。

这个是编码格式的异常,因为在爬虫元服务的对接中,通过http发送数据的时候,打包下来的数据封装的格式不对

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=‘}

因为JSON中并没有单引号,仅有双引号,所以我们需要把单引号替换成双引号了

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

方式有多种,比如用正则

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

还可以同简单的字符串处理

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

以下是系统的异常抛出

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)

以上是关于django-关于JSON编码格式的异常处理的主要内容,如果未能解决你的问题,请参考以下文章

Golang 处理 Json:编码

JavaCV升级1.5.6之后遇到h265/hevc编码的视频无法打开编解码器avcodec_open2() error -1:Could not open video codec异常解决办法(代码片

关于json编码时间格式的转换

关于异常处理

springboot统一返回json数据格式并配置系统异常拦截

重写Laravel异常处理类