I am trying to save high scores for a game and also load it in high score section, but the way I am saving adds more than one record to the JSON file. The problem is while loading, I get the error json.decoder.JSONDecodeError: Extra data
only when there is more than one record.
I am pretty sure this is my problem but me being a starter I cannot make sense out of it.
what I am saving
score = {
"score" : round_counter,
"name" : player["name"],
"hp left" : player["hitpoints"]
}
how I am saving it
if os.path.isfile('score.json'):
print("your score has been added")
json_dump = json.dumps(score)
f = open("score.json","a")
f.write(json_dump)
f.close()
else :
print ("database doesn't exist so it was created!")
json_dump = json.dumps(score)
f = open("score.json","x")
f.write(json_dump)
f.close()
how I am reading it
with open ("score.json") as json_data:
data = json.load(json_data)
print(data)
It works for the first run but when there are 2 records in .json file I cannot read it. I don't know if I need more complete reading code or the way I am saving multiple dictionaries in .json is in its root wrong.