You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python+Flask实现REST JSON服务器的本地JSON文件存储?

解决方案

问题出在你直接将单个字典转成字符串追加到文件,导致文件内容不是合法的JSON数组,读取后只能得到字符串列表。正确的做法是始终维护完整的JSON数组,每次操作都加载整个数组,修改后再整体写入文件。

修改后的代码

首先导入json模块,用于处理JSON的序列化和反序列化:

import json
from flask import Flask, request, jsonify

app = Flask(__name__)

def create(name):
    # 读取现有数据,处理文件不存在的情况
    try:
        with open('static/notes.json', 'r', encoding='utf-8') as f:
            records = json.load(f)
    except FileNotFoundError:
        records = []  # 文件不存在时初始化空数组
    
    # 生成新记录的ID(简单实现:现有记录数+1,如有删除需求可改用UUID)
    new_id = len(records) + 1
    new_record = {'id': new_id, 'name': name}
    records.append(new_record)
    
    # 将更新后的数组写入文件,indent参数让JSON格式更易读
    with open('static/notes.json', 'w', encoding='utf-8') as f:
        json.dump(records, f, indent=2)
    
    return new_record

def get_data():
    try:
        with open('static/notes.json', 'r', encoding='utf-8') as f:
            records = json.load(f)
    except FileNotFoundError:
        records = []
    return records

# Flask路由示例
@app.route('/records', methods=['GET'])
def get_records():
    return jsonify(get_data())

@app.route('/records', methods=['POST'])
def add_record():
    data = request.get_json()
    if not data or 'name' not in data:
        return jsonify({'error': 'Missing required field: name'}), 400
    new_record = create(data['name'])
    return jsonify(new_record), 201

if __name__ == '__main__':
    app.run(debug=True)

关键说明

  1. 文件格式:用.json后缀存储合法的JSON数组,而非纯文本。文件内容始终是[{}, {}, ...]的格式,完全匹配你的需求。
  2. 安全操作:使用with语句自动管理文件打开/关闭,避免资源泄漏和手动关闭的遗漏。
  3. ID生成优化:示例中用len(records)+1生成ID,若需要更稳定的唯一ID(比如支持删除记录后不重复),可改用uuid模块:
    import uuid
    new_id = str(uuid.uuid4())  # 生成全局唯一的字符串ID
    
  4. 原代码bug修复:你原代码中create函数定义了record变量,但写入的是未定义的note,这会导致运行报错,已在修改后的代码中修复。

内容的提问来源于stack exchange,提问作者MaximoConn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:20:34