JSON load()返回JSONDecodeError:期望值



所以我正在制作一个使用JSON的投票/投票系统,当我编码它时我遇到了这个错误:

Traceback (most recent call last):
File "C:UsersooichPycharmProjects16dec2022main.py", line 48, in <module>
poll()
File "C:UsersooichPycharmProjects16dec2022main.py", line 32, in poll
fp = json.load(f)
File "C:Python310libjson__init__.py", line 293, in load
return loads(fp.read(),
File "C:Python310libjson__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:Python310libjsondecoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:Python310libjsondecoder.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)

我不能完全理解它的意思,因为我已经6个多月没有碰过代码了。

下面是我的代码:

import json
def poll():
with open("poll.json", "r") as f:
fp = json.load(f)
le = fp.keys()
print(f"What would you like to vote?n {le}")
i = input("Please write: ")
if fp.get(i) is None:
print("Key not found.")
return False
with open("poll.json", "w") as fe:
fep = json.load(fe)
fep[i] += 1
json.dump(fep, fe)
print("Voted!")
return True

poll()

请让我知道,如果我错过了什么,或者你知道如何解决它。谢谢。

我猜你的json文件是空的,当我的json填充"poll.json"是空的。使用json

poll.json

{"plop": 0}

和这个python

import json
def poll():
with open("poll.json", "r") as f:
fp = json.load(f)
le = fp.keys()
print(f"What would you like to vote?n {le}")
i = input("Please write: ")
if fp.get(i) is None:
print("Key not found.")
return False
with open("poll.json", "w") as f:
fp[i] += 1
json.dump(fp, f)
print("Voted!")
return True
poll()

result for ok

你想投哪一票?dict_keys(['声音'])请写:扑通投票!

如果json中没有键,则返回你想投哪一票?dict_keys(['声音'])请写:不未找到密钥

相关内容

  • 没有找到相关文章