Python闪卡APP开发中JSON文件跨平台更新异常求助
闪卡APP JSON数据存储问题修复
问题概述
开发闪卡APP时,需将问答内容以字典格式保存到JSON文件。更新数据时,旧数据要么被覆盖,要么直接追加到文件,添加2组问答后触发JSON解析错误。
错误信息
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/json/decoder.py", line 340, in decode raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 4 column 2 (char 52)
现有代码
def add_question_to_list(self): new_question = self.add_question_entry.get() new_answer = self.add_answer_entry.get() question_dict = { "Question": new_question, "Answer": new_answer, } try: with open('math.json', "r") as data_file: data = json.load(data_file) print("got here 1") except FileNotFoundError: with open('math.json', "w") as data_file: json.dump(question_dict, data_file, indent=4) else: data.update(question_dict) print("got here 2") with open("math.json", "a") as data_file: json.dump(data, data_file, indent=4) finally: self.add_question_entry.delete(0, END) self.add_answer_entry.delete(0, END) print(question_dict) print("got here 3")
生成的非法JSON内容
{ "Question": "yhnyhn", "Answer": "thnhtg" }{ "Question": "yhnty", "Answer": "tyhntyh" }
问题根源
- 数据结构错误:单个问答字典直接作为顶层对象存储,后续添加新问答时,
data.update(question_dict)会覆盖原有问答(字典键名重复),且追加模式写入导致文件存在多个独立JSON对象,违反JSON规范(JSON文件只能有一个顶层值)。 - 写入模式错误:使用
"a"追加模式会在文件末尾直接写入新内容,导致多个JSON对象拼接,无法被正常解析。
修复方案
将问答数据存储为JSON数组(顶层是列表),每次添加新问答时向列表追加元素,再用写入模式覆盖整个文件,保证JSON格式合法。
修改后的代码
def add_question_to_list(self): new_question = self.add_question_entry.get() new_answer = self.add_answer_entry.get() question_dict = { "Question": new_question, "Answer": new_answer, } try: with open('math.json', "r") as data_file: data = json.load(data_file) print("got here 1") except FileNotFoundError: # 首次创建文件时,存入包含单个问答的列表 with open('math.json', "w") as data_file: json.dump([question_dict], data_file, indent=4) else: # 向列表中添加新问答,避免覆盖原有内容 data.append(question_dict) print("got here 2") # 用写入模式覆盖整个文件,保证JSON格式合法 with open("math.json", "w") as data_file: json.dump(data, data_file, indent=4) finally: self.add_question_entry.delete(0, END) self.add_answer_entry.delete(0, END) print(question_dict) print("got here 3")
修改要点
- 首次创建文件时,写入列表包裹的问答字典(
[question_dict]),确保顶层是数组。 - 读取现有数据后,用
data.append(question_dict)追加新问答,而非update(避免覆盖)。 - 写入文件时使用
"w"模式覆盖整个文件,保证始终只有一个顶层数组,符合JSON规范。
内容的提问来源于stack exchange,提问作者Dillon Franklin
相关产品推荐
相关产品推荐

