Python Flask写入JSON文件时无法添加闭合方括号的问题求助
问题分析与解决方案
首先,核心问题是当前的data.json是不完整的无效JSON(缺少闭合方括号),导致/end路由里的json.load(f)直接抛出JSON解码错误,后续写入闭合括号的代码根本没机会执行,所以括号加不上。
快速修复现有文件
先手动打开data.json,在最后一行加上]并保存,再测试/end路由,就能正常生成完整JSON。
彻底解决:避免生成不完整JSON
你现在用追加模式写JSON的方式本身就容易导致文件不完整(比如服务意外中断、用户未调用/end路由),建议改成每次写入完整的JSON数组:
修改home路由的POST逻辑:
@app.route('/', methods=["GET", "POST"]) def home(): if request.method == 'POST': data = request.form # 读取现有数据,处理文件不存在或无效的情况 try: with open("./data.json", "r") as f: tasks_data = json.load(f) except (FileNotFoundError, json.JSONDecodeError): tasks_data = [] # 添加新数据(转成dict,因为request.form是ImmutableMultiDict) tasks_data.append(dict(data)) # 写入完整的JSON数组,带格式化缩进 with open("./data.json", "w") as f: json.dump(tasks_data, f, indent=2) return render_template('home.html')
这样每次提交数据都会直接生成完整的JSON文件,不需要再依赖/end路由补括号,从根源避免文件不完整问题。
如果一定要保留/end路由
若需要保留/end路由收尾,要先处理不完整的JSON内容,修改后的代码:
@app.route('/end', methods=["GET", "POST"]) def end(): # 读取文件内容,手动修复不完整的JSON try: with open("./data.json", "r") as f: content = f.read().strip() # 检查是否缺少闭合方括号,补上 if content and not content.endswith(']'): content += '\n]' data = json.loads(content) except (FileNotFoundError, json.JSONDecodeError): data = [] # 重新写入完整格式化的JSON with open("./data.json", "w") as f: json.dump(data, f, indent=2) return render_template('home.html')
这样即使文件不完整,也能先修复再解析,最后写入完整JSON。
内容的提问来源于stack exchange,提问作者DYLAN VURBIER
相关产品推荐
相关产品推荐

