Python колбу добавить в JSON - PullRequest
0 голосов
/ 18 января 2019

Я пытаюсь создать ускоренный веб-сайт на python3 с флягой. Я хочу иметь команды. Я сохраняю команды в файле .json. Но я не могу понять, как добавить больше команд. сначала сохраните файл в var с именем team, затем я создам новый var с именем team_cr и сохраню там новую команду. тогда я пытаюсь объединить два вар. Но это не работает

Файл 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

1 Ответ

0 голосов
/ 18 января 2019

Этот фрагмент кода создает кортеж, когда похоже, что вы пытаетесь добавить команду в свой список, который был загружен из 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})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...