Python JSON操作报错:JSONDecodeError: Extra Data问题求助
解决JSON写入读取时的JSONDecodeError问题
我尝试将字典写入JSON文件,后续在代码中搜索该JSON字典的键以加载并打印关联值,但执行写入操作时持续报错。
写入数据的代码
password_dictionary = {} with open('dictionary.json', 'a') as f: dictionary = "dictionary.json" # 加密用户输入的密码并写入JSON文件 def encrypt_and_dump(username, password): e_password = password.encode('utf-8') encrypted = k.encrypt(e_password) d_encrypted = encrypted.decode('utf-8') a = {site: [username, d_encrypted]} try: with open(dictionary, 'r') as f: password_dictionary = json.load(f) except FileNotFoundError: password_dictionary = {} password_dictionary.update(a) with open(dictionary, 'w') as f: json.dump(password_dictionary, f)
加载并搜索信息的代码
def search_and_decrypt(): r_site = str(input("Enter the Site Name to retrieve your credentials (Password Manager is case sensitive.): ")) with open(dictionary, 'r') as f: password_dictionary = json.load(f) if f.readable() else {} for site, user_pass in password_dictionary.items(): if site == r_site: print("ACCOUNT FOUND") c_password = str(pwinput.pwinput("Confirm your Password Manager password to decrypt login credentials: ")) if c_password == m_password: decrypt_user_pass = k.decrypt(user_pass) print(decrypt_user_pass) else: print("Site Account not found.")
报错信息
File "/Users/makaylagalbraith/Documents/Python/PasswordManager.py", line 138, in <module> encrypt_and_dump(username2, c_password2) File "/Users/makaylagalbraith/Documents/Python/PasswordManager.py", line 72, in encrypt_and_dump password_dictionary = json.load(f) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/json/__init__.py", line 293, in load return loads(fp.read(), File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/json/__init__.py", line 346, in loads return _default_decoder.decode(s) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/json/decoder.py", line 340, in decode raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 1 column 3 (char 2)
问题原因与修复方案
1. 初始文件操作损坏JSON结构
开头的with open('dictionary.json', 'a') as f:会创建空文件或向现有文件追加空内容,空文件不属于有效的JSON格式,后续json.load读取时直接触发解码错误。
修复:删除这段多余的代码,函数内部已包含完整的文件读写逻辑。
2. site变量未定义
encrypt_and_dump函数中a = {site: [username, d_encrypted]}的site未作为参数传入,会触发NameError,必须将site添加为函数参数。
3. 修复已损坏的JSON文件
当前dictionary.json已因错误操作变成无效JSON,需手动删除该文件,让代码首次运行时重新创建有效的JSON结构。
4. 搜索解密函数逻辑修正
user_pass是包含用户名和加密密码的列表,解密时需取第二个元素,且要转回字节类型(加密时先编码为字节,解密后转字符串存储)。- 错误提示"Site Account not found."位置错误,应放在密码验证失败场景;遍历结束后未找到站点也需给出提示。
修复后的完整代码片段
修复后的写入函数
import json # 假设k和m_password是已定义的加密密钥和管理密码 def encrypt_and_dump(site, username, password): e_password = password.encode('utf-8') encrypted = k.encrypt(e_password) d_encrypted = encrypted.decode('utf-8') new_entry = {site: [username, d_encrypted]} try: with open('dictionary.json', 'r') as f: password_dictionary = json.load(f) except (FileNotFoundError, json.JSONDecodeError): # 处理文件不存在或内容无效的情况 password_dictionary = {} password_dictionary.update(new_entry) with open('dictionary.json', 'w') as f: json.dump(password_dictionary, f)
修复后的搜索解密函数
def search_and_decrypt(): r_site = input("Enter the Site Name to retrieve your credentials (Password Manager is case sensitive.): ") try: with open('dictionary.json', 'r') as f: password_dictionary = json.load(f) except (FileNotFoundError, json.JSONDecodeError): password_dictionary = {} found = False for site, user_pass in password_dictionary.items(): if site == r_site: found = True print("ACCOUNT FOUND") c_password = pwinput.pwinput("Confirm your Password Manager password to decrypt login credentials: ") if c_password == m_password: # 取出加密密码字符串,转回字节后解密 encrypted_pass = user_pass[1].encode('utf-8') decrypt_user_pass = k.decrypt(encrypted_pass).decode('utf-8') print(f"Username: {user_pass[0]}") print(f"Password: {decrypt_user_pass}") else: print("Incorrect manager password.") break if not found: print("Site Account not found.")
内容的提问来源于stack exchange,提问作者Makayla Galbraith
相关产品推荐
相关产品推荐

