简体   繁体   中英

How to read a json file with more than one records

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.

In order to store more than one JSON record, use an array, as when loading you can just load JSON types (an an array is the ideal JSON type you're looking for for that use case).

In that case, to read all scores:

scores = []
with open ("score.json") as json_data:
    scores = json.load(json_data)

But most important, to write them to a file:

scores.append(score)
json_dump = json.dumps(scores)
f = open("score.json","w")
f.write(json_dump)
f.close()    

Update The last code can also be written using json.dump :

scores.append(score)
f = open("score.json","w")
json.dump(scores, f)
f.write(json_dump)
f.close()    

The way your code is written, it will append score dictionaries instead of adding an object in an array of scores.

If you check the output file score.json it will look like {...}{...}{...} whereas it should be like [{...},{...},{...}]

You can read the file line by line, every line will contain a valid JSON object:

with open('score.json') as fp:
    for line in fp:
        data = json.loads(line)
        # do something with data

Or if you need everything in one object:

with open('score.json') as fp:
    data = []
    for line in fp:
        data.append(json.loads(line))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM