json errors when appending data with Python

Viewed 95

Good day.

I have a small password generator program and I want to save the created passwords into a json file (append each time) so I can add them to an SQLITE3 database.

Just trying to do the append functionality I receive several errors that I don't understand. Here are the errors I receive and below that is the code itself.

I'm quite new to Python so additional details are welcomed.

Traceback (most recent call last): File "C:\Users\whitmech\OneDrive - Six Continents Hotels, Inc\04 - Python\02_Mosh_Python_Course\Py_Projects\PWGenerator.py", line 32, in data = json.load(file) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\json_init_.py", line 293, in load return loads(fp.read(), File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\json_init_.py", line 346, in loads return _default_decoder.decode(s) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

import random
import string
import sqlite3
import json
from pathlib import Path

print('hello, Welcome to Password generator!')

# input the length of password
length = int(input('\nEnter the length of password: '))

# define data
lower = string.ascii_lowercase
upper = string.ascii_uppercase
num = string.digits
symbols = string.punctuation
# string.ascii_letters

# combine the data
all = lower + upper + num + symbols

# use random
temp = random.sample(all, length)

# create the password
password = "".join(temp)

filename = 'saved.json'
entry = {password}

with open(filename, "r+") as file:
    data = json.load(file)
    data.append(entry)
    file.seek(0)
    json.dump(data, file)

# print the password
print(password)

Update: I've changed the JSON code as directed and it works but when trying to do the SQLite3 code I'm knowing receiving a typeerror

Code:

with open(filename, "r+") as file:
    try:
        data = json.load(file)
        data.append(entry)
    except json.decoder.JSONDecodeError as e:
        data = entry
    file.seek(0)
    json.dump(data, file)

# print the password
print(password)

store = input('Would you like to store the password? ')

if store == "Yes":
    pwStored = json.loads(Path("saved.json").read_text())
    with sqlite3.connect("db.pws") as conn:
        command = "INSERT INTO Passwords VALUES (?)"
        for i in pwStored:
            conn.execute(command, tuple(i.values)) # Error with this code
        conn.commit()
else:
    exit()

Error:

AttributeError: 'str' object has no attribute 'values'

1 Answers

The error is because

  • Your json file is empty, you need to update the following block
entry = [password]

with open(filename, "r+") as file:
    try:
        data = json.load(file)
        data.extend(entry)
    except json.decoder.JSONDecodeError as e:
        data = entry
    file.seek(0)
    json.dump(data, file)
  • Also you are adding password in a set ie., entry, and it will again throw you an error TypeError: Object of type set is not JSON serializable So you need to convert that to either a list or dict

Note: Here I have used entry as a list

Related