[Python] Appending to .json file does not work... error code: json.decoder.JSONDecodeError

Discussão em 'Python' iniciado por Stack, Janeiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    Currently working on optimizing my passwort manager. Heres the code:

    from tkinter import *
    from tkinter import messagebox
    import random
    import string
    import json

    # ---------------------------- PASSWORD GENERATOR ------------------------------- #
    def generate_password():
    password_list = []

    s1 = list(string.ascii_lowercase)
    s2 = list(string.ascii_uppercase)
    s3 = list(string.digits)
    s4 = list(string.punctuation)

    for x in range(4):
    password_list.append(s1[x])
    password_list.append(s2[x])
    password_list.append(s3[x])
    password_list.append(s4[x])

    random.shuffle(password_list)
    password = "".join(password_list)
    password_entry.delete(0, END)
    password_entry.insert(0, password)


    # ---------------------------- SAVE PASSWORD ------------------------------- #


    def add_info():
    website = website_entry.get()
    email_username = email_username_entry.get()
    password = password_entry.get()
    data_dict = {
    website: {
    "email": email_username,
    "password": password,
    }
    }
    try:
    with open("data.json", mode="r") as data_file:
    for line in data_file:
    if website in line:
    messagebox.showerror("ERROR", "Data for this website already exists.")
    data_file.close()
    else:
    with open("data.json", mode="r") as data_file:
    data = json.load(data_file)
    data.update(data_dict)
    with open("data.json", mode="w") as data_file:
    data.dump(data_file, data_dict, indent=4)

    except FileNotFoundError:
    with open("data.json", mode="w+") as data_file:
    json.dump(data_dict, data_file, indent=4)
    finally:
    with open("data.json", mode="r") as data_file:
    data = json.load(data_file)
    data.update(data_dict)
    with open("data.json", mode="w") as data_file:
    json.dump(data_dict, data_file, indent=4)



    Problem is that I cant manage to write to the json file/append new passwords and usernames to it. Any help would be HIGHLY appreciated as im about to crash out man :/

    Tried many variants of if/else, exceptions, finally etc, nothing helped me. When I deleted the file it put the first password/username combo in and then screwed everything over again.

    Continue reading...

Compartilhe esta Página