json.decoder.JSONDecodeError:期望值:尝试写入json文件时,第1行第1列(字符0)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了json.decoder.JSONDecodeError:期望值:尝试写入json文件时,第1行第1列(字符0)相关的知识,希望对你有一定的参考价值。
我得到的错误是:
忽略on_message中的异常
Traceback (most recent call last):
File "C:\Users\Lucas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Lucas\python\lvlBot\main.py", line 34, in on_message
users = json.load(f)
File "C:\Users\Lucas\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\Lucas\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\Lucas\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Lucas\AppData\Local\Programs\Python\Python38-32\lib\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)
import discord
import json
import os
from discord.ext import commands
client = commands.Bot(command_prefix= '::')
#path = os.path.dirname(__file__)
os.chdir(r'c:\Users\Lucas\python\lvlBot')
@client.event
async def on_ready():
print("Bot is running...")
@client.event
async def on_member_join(member):
with open('users.json', 'r') as f:
users = json.load(f)
await update_data(users, member)
with open('users.json', 'w') as f:
json.dump(users, f)
@client.event
async def on_message(message):
with open('users.json', 'r') as f:
users = json.load(f)
await update_data(users, message.author)
await add_experience(users, message.author, 5)
await level_up(users, message.author, message.channel)
with open('users.json', 'w') as f:
json.dump(users, f)
async def update_data(users, user):
if not user.id in users:
users[user.id] =
users[user.id]['experience'] = 0
users[user.id]['level'] = 1
async def add_experience(users, user, exp):
user[user.id]['experience'] += exp
async def level_up(users, user, channel):
experience = user[user.id]['experience']
lvl_start = user[user.id]['level']
lvl_end = int(experience ** (1/4))
if lvl_start < lvl_end:
await channel.send(channel, ' har levlat upp till '.format(user.mention, lvl_end))
users[user.id]['level'] = lvl_end
#print(path)
client.run('')
答案
对于第一个用户,users.json
为空,因此导致最初,您将获得json.decoder.JSONDecodeError:
。也许值得检查
with open('users.json', 'r') as f:
users = json.load(f)
返回None
。
if not users:
users = # or users = [] if you have a JSONArray
await update_data(users, member)
# ...
另一答案
尝试简化逻辑以仅加载json文件。
查看您的错误消息:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
您会看到错误是文件中没有内容(“字符0应该是一个值”)。
以上是关于json.decoder.JSONDecodeError:期望值:尝试写入json文件时,第1行第1列(字符0)的主要内容,如果未能解决你的问题,请参考以下文章