【问题标题】:JSON Exception Handling Syntax unclear to me -- JSONDecodeError我不清楚 JSON 异常处理语法——JSONDecodeError
【发布时间】:2021-04-16 06:31:49
【问题描述】:

我正在使用 JSON 从 API 获取一些数据,如果输入的 URL 错误(很有可能)JSON 文件返回:“未知符号”

错误信息如下:(不要害怕,它只是相关信息,向下滚动到底部我已突出显示主要错误。)

Environment:



Request Method: POST

Request URL: http://127.0.0.1:8000/buy/



Django Version: 3.1.2

Python Version: 3.7.0

Installed Applications:

['django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'accounts']

Installed Middleware:

['django.middleware.security.SecurityMiddleware',

'django.contrib.sessions.middleware.SessionMiddleware',

'django.middleware.common.CommonMiddleware',

'django.middleware.csrf.CsrfViewMiddleware',

'django.contrib.auth.middleware.AuthenticationMiddleware',

'django.contrib.messages.middleware.MessageMiddleware',

'django.middleware.clickjacking.XFrameOptionsMiddleware']







Traceback (most recent call last):

File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 353, in raw_decode

obj, end = self.scan_once(s, idx)



During handling of the above exception (0), another exception occurred:

File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner

response = get_response(request)

File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response

response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view

return view_func(request, *args, **kwargs)

File "C:\Users\VARDHAN\Desktop\python websites\trading_website\accounts\views.py", line 116, in buy

json_data = requests.get(url).json()

File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\models.py", line 900, in json

return complexjson.loads(self.text, **kwargs)

File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads

return _default_decoder.decode(s)

File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode

obj, end = self.raw_decode(s, idx=_w(s, 0).end())

File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 355, in raw_decode

raise JSONDecodeError("Expecting value", s, err.value) from None



**Exception Type: JSONDecodeError at /buy/
Exception Value: Expecting value: line 1 column 1 (char 0)**


我尝试过的修复:

try:
    ....
               
except JSONDecodeError:
                       messages.error(request, "The is ticker is either wrong or not supported. Please try another one :)")
                       return redirect ("buy")

【问题讨论】:

  • 可能json_data 格式不正确。先试试看
  • 哦,它只是“json_data = requests.get(url).json()”的一个变量,它可以正确处理具有正确数据的情况,我只是不知道如何处理有错误。

标签: python json django django-views


【解决方案1】:

当您调用 API 时,您的 API 调用可能会失败并仅返回字符串或空响应。我建议您首先检查您的响应的状态代码,如下所示,然后处理 json 数据。

    data = requests.get(url)
    if data.status != 200:
        raise Exception("Error") 
   json_data = data.json()

【讨论】:

  • 大家好,非常感谢您的帮助!对此,我真的非常感激!老实说,我尊重您的时间,并且非常感谢您付出一些时间来帮助别人的事实!这告诉我你是一个好人我在这个解决方案中遇到了一些错误,但我终于解决了,我无法弄清楚你使用的 HTTP 模块,但是,这给了我一个想法,我使用了这个:这有效就像一个魅力,老实说,如果没有你的帮助,我不可能得到这个!我整个上午都在试图弄清楚这一点,现在我终于明白了,感觉棒极了!
  • 顺便说一句,“data.status”的语法现在已更改为“data.status_code”,请注意,感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
相关资源
最近更新 更多