jsonは厳格でない問題を処理して、“json.decoder.JSOnDecodeError”の解決方法が現れます

4660 ワード

postリクエストを使用する場合、場合によっては、特に言語間の場合、JSONはこのように入力される可能性があります.
{
    "btitle": "    (   )",
    "bpub_date": "1990-02-03"
}

コード呼び出し時に、
json.loads(json_str)

次のエラーを報告
Internal Server Error: /books/
Traceback (most recent call last):
  File "/Users/kungs/django_py3_1.11/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/kungs/django_py3_1.11/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/kungs/django_py3_1.11/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/kungs/django_py3_1.11/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/kungs/django_py3_1.11/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/kungs/Desktop/code/demo/booktest/views.py", line 65, in post
    req_data = json.loads(json_str)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Invalid control character at: line 2 column 18 (char 19)

解決策:上のコードを
json.loads(json_str, strict=False)

問題解決~