JSON错误:json.decoder.JSONDecodeError:预期值:第1行第1列(字符0)

时间:2019-04-19 19:18:24

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

我正在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)

编辑:此问题已解决,如果您遇到相同的问题,请在下面检查我的答案。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

好吧,我知道了。我需要取消缩进一次该块:

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')