【问题标题】:JSON Error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)JSON 错误:json.decoder.JSONDecodeError:预期值:第 1 行第 1 列(字符 0)
【发布时间】:2019-09-10 00:23:31
【问题描述】:

我正在 discord.py (python 3.6.8) 中为我的 discord 机器人制作调平系统,但我不断收到此错误,我无法真正理解它的含义。

这是我的代码:

import random, asyncio, os, discord, json, time
from discord.ext.commands import Bot

BOT_PREFIX = ("&")
client = Bot(command_prefix=BOT_PREFIX)
client.remove_command('help')

if not os.path.exists('users.json'):
    open('users.json', 'w').close()

@client.event
async def on_message(message):
    with open("users.json", "r") as f:
        users = json.load(f)

        if message.author.bot:
            return
        if message.channel.is_private:
            return
        else:
            await update_data(users, message.author, message.server)
            number = random.randint(5,10)
            await add_experience(users, message.author, number, message.server)
            await level_up(users, message.author, message.channel, message.server)

        with open("users.json", "w") as f:
            json.dump(users, f)
    await client.process_commands(message)

async def update_data(users, user, server):
    if not user.id + "-" + server.id in users:
        users[user.id + "-" + server.id] = {}
        users[user.id + "-" + server.id]["experience"] = 0
        users[user.id + "-" + server.id]["level"] = 0
        users[user.id + "-" + server.id]["last_message"] = 0

async def add_experience(users, user, exp, server):
    if time.time() - users[user.id + "-" + server.id]["last_message"] > 5:
        users[user.id + "-" + server.id]["experience"] += exp
        users[user.id + "-" + server.id]["last_message"] = time.time()
    else:
        return

async def level_up(users, user, channel, server):
    experience = users[user.id + "-" + server.id]["experience"]
    lvl_start = users[user.id + "-" + server.id]["level"]
    lvl_end = int(experience ** (1/4))

    if lvl_start < lvl_end:
        await client.send_message(channel, f"{user.mention}, has leveled up to level {lvl_end}!")
        users[user.id + "-" + server.id]["level"] = lvl_end


print('[BOT SUCCESSFULLY STARTED]\n\n')
client.run('YOUR_TOKEN_HERE')

这是我的错误:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\NeverEndingCycle\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "C:\Users\NeverEndingCycle\Desktop\Coding_Stuff\Py_Code\Bot_Testing\Logic_Tests\XP-Logic\main.py", line 14, in on_message
    users = json.load(f)
  File "C:\Users\NeverEndingCycle\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "C:\Users\NeverEndingCycle\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Users\NeverEndingCycle\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\NeverEndingCycle\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

编辑:这个问题已经解决了,如果你有同样的问题,请在下面查看我的回答。

【问题讨论】:

  • "告诉添加更多详细信息" 你可以添加部分 JSON 有效负载吗?该错误会告诉您问题出在哪里。它说有效载荷中的第一个字符无效。在users = json.load(f) 之前添加print(f) 并将其添加到您的问题中,或者只是添加users.json 的内容。之后我们可以提供帮助。
  • 当我打印 'f' 时,我得到这个:&lt;_io.TextIOWrapper name='users.json' mode='r' encoding='cp1252'&gt; 数据不会附加到 users.json,所以我没有要添加的内容。
  • 您打开文件以从中读取,然后在读取上下文中打开文件以对其进行写入。你不能同时做这两件事,我的坏事是print(f.read())
  • 当我这样做时,实际上没有任何打印。我的 json 文件是空的,所以我相信没有什么可以打印的。
  • 好吧,我想通了。检查我的答案。

标签: python json python-3.x python-3.6 discord.py


【解决方案1】:

该错误是因为您尝试加载的不是 json 并且未正确处理。

您可以知道这一点,因为json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) 第 1 行第 1 列 char 0 表示根本没有读取 json。当错误指向第一个位置字符时,表示该内容的格式对于要读取的 json 不正确。

【讨论】:

  • 那么我做错了什么使我的数据不正确而无法读取 json?我该如何解决这个问题?
  • 我们需要查看该文件的内容。您确定该文件是准确的 JSON 吗?
  • 文件完全是空的,我问这个问题的全部原因是因为这个错误阻止我向 JSON 文件添加任何数据。
  • 那是你的问题。错误出现在带有打开读取循环的 json.load(f) 上。这是失败的,因为文件是空的,因此不能作为 json 读取。
  • 好吧,我想通了。检查我的答案。
【解决方案2】:

好的,我想通了。我需要一次取消缩进这个块:

with open("users.json", "w") as f: 
    json.dump(users, f)

这就是没有保存数据的原因。至于错误,我相信@GiraffeMan91 是对的。因为没有保存数据并且 JSON 是空的,所以没有要解码的内容,因此给出了 JSONDecodeErorr。

这是上面代码的工作版本:

import random, asyncio, os, discord, json, time
from discord.ext.commands import Bot

BOT_PREFIX = ("&")
client = Bot(command_prefix=BOT_PREFIX)
client.remove_command('help')

if not os.path.exists('users.json'):
    open('users.json', 'w').close()

@client.event
async def on_message(message):
    with open("users.json", "r") as f:
        users = json.load(f)

        if message.author.bot:
            return
        if message.channel.is_private:
            return
        else:
            await update_data(users, message.author, message.server)
            number = random.randint(5,10)
            await add_experience(users, message.author, number, message.server)
            await level_up(users, message.author, message.channel, message.server)

    with open("users.json", "w") as f:
        json.dump(users, f)
    await client.process_commands(message)

async def update_data(users, user, server):
    if not user.id + "-" + server.id in users:
        users[user.id + "-" + server.id] = {}
        users[user.id + "-" + server.id]["experience"] = 0
        users[user.id + "-" + server.id]["level"] = 0
        users[user.id + "-" + server.id]["last_message"] = 0

async def add_experience(users, user, exp, server):
    if time.time() - users[user.id + "-" + server.id]["last_message"] > 5:
        users[user.id + "-" + server.id]["experience"] += exp
        users[user.id + "-" + server.id]["last_message"] = time.time()
    else:
        return

async def level_up(users, user, channel, server):
    experience = users[user.id + "-" + server.id]["experience"]
    lvl_start = users[user.id + "-" + server.id]["level"]
    lvl_end = int(experience ** (1/4))

    if lvl_start < lvl_end:
        await client.send_message(channel, f"{user.mention}, has leveled up to level {lvl_end}!")
        users[user.id + "-" + server.id]["level"] = lvl_end


print('[BOT SUCCESSFULLY STARTED]\n\n')
client.run('YOUR_TOKEN_HERE')

【讨论】:

    猜你喜欢
    • 2020-01-02
    • 1970-01-01
    • 2020-08-16
    • 2016-03-03
    • 2019-06-10
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2017-05-09
    相关资源
    最近更新 更多