简体   繁体   English

如何读取包含多条记录的json文件

[英]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.我正在尝试保存游戏的高分并将其加载到高分部分,但我保存的方式向 JSON 文件添加了多个记录。 The problem is while loading, I get the error json.decoder.JSONDecodeError: Extra data only when there is more than one record.问题是在加载时,我收到错误json.decoder.JSONDecodeError: Extra data only 当有多个记录时。

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.它适用于第一次运行,但是当 .json 文件中有 2 条记录时,我无法读取它。 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.我不知道我是否需要更完整的阅读代码,或者我在 .json 中保存多个字典的方式是根本错误的。

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).为了存储多个 JSON 记录,请使用数组,因为在加载时您可以只加载 JSON 类型(数组是您正在寻找的用于该用例的理想 JSON 类型)。

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 :更新最后的代码也可以使用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 [{...},{...},{...}]如果你检查输出文件 score.json 它看起来像 {...}{...}{...} 而它应该像 [{...},{...},{... }]

You can read the file line by line, every line will contain a valid JSON object:您可以逐行读取文件,每一行都将包含一个有效的 JSON 对象:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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