python - Appending to .json file does not work... error code: json.decoder.JSONDecodeError - Stack Overflow

admin2025-04-21  2

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.

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.

Share Improve this question edited Jan 22 at 22:16 kutari studios asked Jan 22 at 22:15 kutari studioskutari studios 112 bronze badges 2
  • It would help if you could put the entire error output into your question as a code block. – Mark Ransom Commented Jan 22 at 23:03
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Bot Commented Jan 23 at 5:13
Add a comment  | 

1 Answer 1

Reset to default 0

I suspect your problem may relate to this section of your code

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)

generally in python, when opening a file in this manner

with open("filename") as file:
    contents = file.read()
    # more file things

the with X as Y: block handles closing the file after you open it, when the block ends.

In this case, all within the with block, you read the file, close it, open it (and implicitly close it when the first internal with block ends), and finally open/close it again (with the second internal with block). However, after all this work, when the outer with block ends, I believe it closes the file again, which may overwrite your work.

I would recommend restructuring to the following format:

# read data from file
with open("data.json", mode="r") as data_file:
    data = json.load(data_file)
    data.update(data_dict)

# check for target website (pseudocode)
if data.json_get(website): # pseudocode function
    # error

# assuming no error, write additional data
with open("data.json", mode="w") as data_file:
    data.dump(data_file, data_dict, indent=4)

this way your reads and writes are separated, and the file is read a minimal amount of times (which could be important if it's a very large file).

Finally, I would advise you to parse the JSON data to check for pre-existing accounts, rather than relying on string matching.

  • URLs may be present in the passwords of a user, whether they utilize websites in their passwords, or short URLs like x.com happen to be randomly generated
  • in the case that a user adds their email account login after their other logins, the current code may match the URL in the email field

best of luck!

转载请注明原文地址:http://anycun.com/QandA/1745226338a90468.html