json在使用Python追加数据时出错



大家好。

我有一个小的密码生成器程序,我想把创建的密码保存到一个json文件(每次追加),这样我就可以把它们添加到SQLITE3数据库。

只是试图做附加功能,我收到几个错误,我不明白。以下是我收到的错误,下面是代码本身。

我对Python很陌生,所以欢迎更多的细节。

Traceback(最近一次调用):文件"C:UserswhitmechOneDrive - Six continent Hotels, Inc4 - Python2_Mosh_Python_CoursePy_ProjectsPWGenerator.py&quotData = json.load(文件)文件"C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0libjson_init_.py",第293行,在加载返回负载(fp.read (),文件"C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0libjson_init_.py",第346行返回_default_decoder.decode(年代)文件"C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0libjsondecoder.py",第337行,在解码Obj, end = self。Raw_decode (s, idx=_w(s, 0).end())文件"C:Program FilesWindowsApps pythonsoftwarefoundation . python . 3.103.3.10.1264.0 _x64__qbz5n2kfra8p0libjsondecoder.py",第355行,在raw_decode .py&quot从None抛出JSONDecodeError(" expected value", s, error .value)json.decoder.JSONDecodeError:期望值:第1行第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)

更新:我已经按照指示更改了JSON代码,它可以工作,但当试图做SQLite3代码时,我知道收到一个类型错误

代码:

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()

错误:

AttributeError: 'str' object没有属性'values'

错误是因为

  • 你的json文件是空的,你需要更新以下块
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)
  • 您还在设置ie中添加密码。,entry,它会再次抛出错误TypeError: Object of type set is not JSON serializable所以你需要将其转换为listdict

注意:这里我使用entry作为列表

最新更新