尝试使用json.loads从外部Json文件导入字典,但是当我这样做时,我会收到一条错误消息。
import json
import random
winner = "None"
winners = 0
class player:
def __init__(self, playernum):
self.playernum = playernum
self.score = random.randint(1,6)
self.name = "foo"
player1 = player(1)
player2 = player(2)
if player1.score > player2.score:
winner = player1.name
winners = player1.score
elif player2.score > player1.score:
winner = player2.name
winners = player2.score
with open("highscores.txt", "a") as f:
json.dump({winner : winners}, f)
f.close()
with open("highscores.txt", "r") as f:
scores = json.load(f)
f.close()
print(scores)
Highscores.txt当前包含7个词典; {“丹尼尔”:71} {“乔纳森”:26} {“乔纳森”:58} {“丹尼尔”:90} {“乔纳森”:57} {“乔纳森”:80} {“乔纳森”:50} < / p>
它是否应该打印出文件,该文件应该由“ winner:winners”字典组成? 相反,我收到此错误消息:
Traceback (most recent call last):
File "C:/Users/jonat/AppData/Local/Programs/Python/Python36-32/neacode.py", line 119, in <module>
scores = json.load(f)
File "C:\Users\jonat\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\jonat\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Users\jonat\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 342, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 15 (char 14)
为什么?
答案 0 :(得分:1)
这是因为您要将字典附加到文件中,这是无效的json语法:
from io import StringIO
import json
s = '''{"a": 1}
{"b": 2}
{"c": 3}'''
fh = StringIO(s)
json.load(fh) # JSONDecodeError
此外,在以append(json.dump
)模式打开的文件中使用'a'
不会包含换行符,这会产生更糟糕的非json。为了解决这个问题,我将更改您附加到文件的方式:
with open('highscores.txt', 'a') as fh:
obj = json.dumps({winner: winners})+'\n' # note the added newline here
fh.write(obj)
这将允许您逐行读取文件:
with open('highscores.txt', 'r') as fh:
scores = [json.loads(line.strip()) for line in fh]
print(scores)
另外,请注意,您不必致电fh.close()
,因为with
语句将为您解决这个问题