【问题标题】:Python flask add to JSONPython烧瓶添加到JSON
【发布时间】:2023-03-08 02:52:01
【问题描述】:

我正在尝试使用烧瓶在 python3 中创建一个快速运行的网站。我想要有团队。我将团队保存在 .json 文件中。但我不知道如何添加更多团队。首先,将文件保存在一个名为 team 的 var 中,然后我创建一个名为 team_cr 的新 var 并将新团队保存在那里。然后我尝试将这两个变量结合起来。但它不起作用

包含团队的 JSON 文件:

[
{
    "name": "Level8",
    "members": 0,
    "publicID": "",
    "teamColor": "red",
    "games": 0,
    "win": 0,
    "kd": 0
},
{
    "name": "test",
    "members": 0,
    "publicID": "",
    "teamColor": "red",
    "games": 0,
    "win": 0,
    "kd": 0
}
]

Python 服务器端脚本:

@app.route("/team/create", methods=["POST", "GET"])
def team_cr():

    if request.method == "GET": 
         return render_template("team_create.html") #If it is a GET request send team_create.html

    elif request.method == "POST":

        create_team(request.form["name"], request.form["color"]) # Calls the function create_team.

        return render_template("team_suc.html")   #If it is a POST request send team_succses.html


def create_team(name, color):
    with open(path+"/Teams_Public.json") as f:
        team = json.load(f) #Loads the team date to a var.

    with open('Teams_Public.json', 'w') as outfile:
        team_cr = {
                    "name": name, # Adds the name of the team to a JSON
                    "members": 0,
                    "publicID": "",
                    "teamColor": color, # Adds the color of the team to a JSON
                    "games": 0,
                    "win": 0,
                    "kd": 0
        },team #adds the old teams to the new team

        json.dump(team_cr, outfile) #write the json file to disk

【问题讨论】:

  • 我删除了 path+"/Team_Public.json" 并将其替换为 "Team_Public.json"

标签: python json flask


【解决方案1】:

这段代码正在创建一个元组,当您尝试做的是将团队附加到从 json 加载的列表中时。

    team_cr = {
                "name": name, # Adds the name of the team to a JSON
                "members": 0,
                "publicID": "",
                "teamColor": color, # Adds the color of the team to a JSON
                "games": 0,
                "win": 0,
                "kd": 0
    },team

您可以尝试将新的数据位附加到列表中。

team.append({your new data})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多