问题描述
每次我将字典转储到 JSON 文件时,都会添加一对方括号,我不知道如何避免。
我使用“try”写入现有的 JSON 文件(出现问题的地方),除了 JSONDecodeError 写入空的 JSON 文件。 代码如下:
allgrades = []
[...]
currentgrades = {f"name": students_name,"grade": students_grade,"date": date.strftime("%Y-%m-%d %H:%M:%s")
}
allgrades.append(currentgrades)
# Write json file
with open("grades.json","r") as infile:
try:
grades = json.load(infile)
infile.close()
grades.append(allgrades)
with open("grades.json","w") as outfile:
json.dump(grades,outfile)
except JSONDecodeError:
with open("grades.json","w") as outfile:
json.dump(allgrades,outfile)
运行 py 两次后,每个 1 个导出的 dict 的 JSON 文件如下所示:
[{"name": "person1","grade": "4","date": "2021-02-20 10:42:01"},[{"name": "person2","date": "2021-02-20 10:52:52"}]]
有没有一种方法可以让我最终得到一个只被一对方括号包围的 JSON 文件,无论我添加到 JSON 多少次? 即
[{"name": "person1",{"name": "person2","date": "2021-02-20 10:52:52"}]
解决方法
grades.append(allgrades)
allgrades
是一个列表,您将其附加到 grades
- 另一个列表。这将创建一个嵌套列表,这是额外 ]
的来源。
您想要的是用新列表扩展现有列表:
grades.extend(allgrades)
将 allgrades
中的所有条目添加到 grades
- 没有任何嵌套。