1. 程式人生 > >json處理不嚴謹問題,出現"json.decoder.JSONDecodeError"解決辦法

json處理不嚴謹問題,出現"json.decoder.JSONDecodeError"解決辦法

使用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)

問題解決~