【问题标题】:How to add item into a list stored in JSON file如何将项目添加到存储在 JSON 文件中的列表中
【发布时间】:2019-10-21 14:50:07
【问题描述】:

我想将字典添加到我的 JSON 文件中的列表中。

reading = []
reading["game_review"] = {
    "name" : your_name,
    "time" : round(time_result, 2),
    "level" : level+1
}

with open("stat.json", "a") as stats:
    json.dump(reading, stats)

每次我运行代码时,都会在 JSON 文件中创建另一个字典,并将其放在我已经拥有的字典旁边,我希望它将自己添加到字典内的列表中。

已编辑:

with open("stat.json", "r") as stat_read:
        reading = json.loads(stat_read.read())
    reading["game_review"] = {
        "name" : your_name,
        "time" : round(time_result, 2),
        "level" : level+1
    }

    with open("stat.json", "a") as stats:
        json.dump(reading, stats)

已解决:

with open("stats.json", "r") as stat_read:
                reading = json.loads(stat_read.read())
                reading["game_review"].append({
                    "name" : your_name,
                    "time" : round(time_result, 2),
                    "level" : level+1,
                    "date" : date
                })

            with open("stats.json", "w") as stats:
                json.dump(reading, stats)

【问题讨论】:

  • 你为什么不期待? "a"ppend 模式添加到文件末尾。
  • 其中哪一个会添加到列表中?
  • 文件读写模式?他们都不是,他们不关心文件的布局。您需要解析旧内容,根据需要对其进行更新,然后将其写回文件中。
  • 那我现在应该写什么呢?
  • @jonrsharpe 解释的哪一部分不清楚?

标签: python json python-3.x list dictionary


【解决方案1】:

如果您想这样做,请阅读该文件,解析 JSON 内容,然后将 JSON 附加到列表中。然后重新写入文件。 假设一个 JSON 文件有以下内容

{'a':['b','c'],'d':'e'}

那么您可以执行以下操作

with open("data.json") as jfile:
   current_data=json.load(jfile)
current_data['a'].append('f')
with open("data.json","w") as jfile:
   json.dump(current_data,jfile)

文件中的最终内容将是

{'a':['b','c','f'],'d':'e'}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    相关资源
    最近更新 更多