当我尝试加载json文件时,会发生此错误:json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 5 (char 6)
代码:
with open("users.json") as fp:
users = json.load(fp)
我想为我的水准测量系统加载一个名为"users"的json文件,有人能帮忙吗。
全平层系统代码:
try:
with open("users.json") as fp:
users = json.load(fp)
except Exception:
users = {}
def save_users():
with open("users.json", "w+") as fp:
json.dump(users, fp, sort_keys=True, indent=int(4))
def add_points(user: discord.User, points: int):
id = user.id
if id not in users:
users[id] = {}
users[id]["points"] = users[id].get("points", 0) + points
print("{} now has {} points".format(user.name, users[id]["points"]))
save_users()
def get_points(user: discord.User):
id = user.id
if id in users:
return users[id].get("points", 0)
return 0
@client.event
async def on_message(message):
message.content = message.content.lower()
print("{} sent a message".format(message.author.name))
if message.content.lower().startswith("!points"):
embed = discord.Embed(title="You have {} Global Points!".format(get_points(message.author)),
color=0x0061ff)
await message.channel.send(embed=embed)
if message.content.lower().startswith("!rank"):
embed = discord.Embed(title="You have {} Global Points!".format(get_points(message.author)),
color=0x0061ff)
await message.channel.send(embed=embed)
add_points(message.author, 1)
我试过这个:
with open("users.json") as fp:
users = json.load(fp)
def save_users():
with open("users.json", "w+") as fp:
json.dump(users, fp, sort_keys=True, indent=int(4))
def add_points(user: discord.User, points: int):
id = user.id
if id not in users:
users[id] = {}
users[id]["points"] = users[id].get("points", 0) + points
print("{} now has {} points".format(user.name, users[id]["points"]))
save_users()
def get_points(user: discord.User):
id = user.id
if id in users:
return users[id].get("points", 0)
return 0
@client.event
async def on_message(message):
message.content = message.content.lower()
print("{} sent a message".format(message.author.name))
if message.content.lower().startswith("!points"):
embed = discord.Embed(title="You have {} Global Points!".format(get_points(message.author)),
color=0x0061ff)
await message.channel.send(embed=embed)
if message.content.lower().startswith("!rank"):
embed = discord.Embed(title="You have {} Global Points!".format(get_points(message.author)),
color=0x0061ff)
await message.channel.send(embed=embed)
add_points(message.author, 1)
首先,您应该检查json文件的真实性,因为如果字符串错误,您可能会遇到错误
如果json文件路径与您的路径不同,您的代码应该是这样的:with open("path\users.json") as fp:
JSON文件必须采用以下格式:
{"key-1": "value-1", "key-2": "value-2"}
你得到这个错误是因为你正在使用这个:
{'key-1': 'value-1', 'key-2': 'value-2'}
您可以修复JSON转储代码:
def save_users():
with open("users.json", "w+") as fp:
json.dump(str(users).replace("'", '"'), fp, sort_keys=True, indent=int(4))