Python JSONDecodeError报错的调试方法与修复方案
Discord 聊天机器人指令JSON解析报错修复
问题场景
开发Discord机器人聊天指令时,代码运行持续抛出JSON解析类错误。
初始问题代码
@client.command() async def chatbot(ctx, *, msg): chatbot1 = requests.get(f"https://chatbot-api.therealenny1.repl.co/?message={quote(msg)}") resp = chatbot1.json() await ctx.send(resp)
运行报错栈
Ignoring exception in command chatbott: Traceback (most recent call last): File "/home/runner/m/venv/lib/python3.8/site-packages/requests/models.py", line 972, in json return complexjson.loads(self.text, **kwargs) File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/runner/m/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "main.py", line 50, in chatbott resp = chatbot1.json() File "/home/runner/m/venv/lib/python3.8/site-packages/requests/models.py", line 976, in json raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/runner/m/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "/home/runner/m/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "/home/runner/m/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
根因说明
调用的第三方聊天接口返回内容为纯文本格式,并非标准JSON结构。直接调用响应对象的.json()方法尝试解析时,解析器无法从响应内容起始位置识别到合法JSON值,因此触发解析报错。
修复方案
移除错误的JSON解析逻辑,直接读取响应的文本内容即可,修复后代码如下:
@client.command() async def chatbot(ctx, msg): url = f"https://chatbot-api.therealenny1.repl.co/?message={quote(msg)}" data = requests.get(url) await ctx.send(data.text)
内容的提问来源于stack exchange,提问作者Ocryol
相关产品推荐
相关产品推荐

