Per*_*ero 3 python encoding byte json python-3.x
尝试在 JSON 文件中转储字典给了我错误“TypeError: a bytes-like object is required, not 'str'”
我已经尝试删除“encrypt_string”函数的字节转换部分,但它给了我错误“TypeError: a bytes-like object is required, not 'str'”
#!/usr/bin/python3
# Imports
import json
import base64
from cryptography.fernet import Fernet
# Save
def encrypt_string(string, f):
return str(f.encrypt(base64.b64encode(bytes(string,'utf-8'))).decode('utf-8'))
def encrypt_dict(dict):
fk = Fernet.generate_key().decode('utf-8')
f = Fernet(fk)
ed = {}
ed['fk'] = base64.b64encode(bytes(fk, 'utf-8'))
for key, value in dict.items():
ekey = encrypt_string(key, f)
evalue = encrypt_string(value, f)
ed[ekey[::-1]] = evalue[::-1]
return ed
def save_game(slot, savename):
print("Saving file...")
path = 'saves/savegame{0}.json'.format(slot)
data = {
'game': 'Game name here',
'version': 'Version here',
'author': 'Author here',
'savename': str(savename),
}
data = encrypt_dict(data)
with open(path, 'w') as f:
json.dump(data, f)
f.close()
print('Data saved in', path)
# Main
import gamemodule as gm
def main():
print("Running...")
gm.save_game(1, 'test')
input("Press any button to continue...")
Run Code Online (Sandbox Code Playgroud)
我希望程序保存游戏数据的文件,但它只返回“TypeError:需要一个类似字节的对象,而不是‘str’”错误
我认为这与我在 encrypt_dict 函数中对变量进行编码有关,但我不确定,我浏览过与此类似的其他问题,但没有找到任何可以解决我的错误的问题
Ola*_*laf 10
问题是base64.b64encode(bytes(fk, 'utf-8'))
inencrypt_dict
返回一个字节串 (b'NGtUbnNEc2hXZTlsOE1tcWVoVkNOUjMtWVIxcVZrWGV1WlBVcjJ2WkhHST0='
) 而 encrypt_string 返回一个普通字符串(没有前导 b)。JSON 格式仅支持 unicode 字符串。
这可以通过将第 16 行替换encrypt_dict
为
ed['fk'] = base64.b64encode(bytes(fk, 'utf-8')).decode("ascii")
Run Code Online (Sandbox Code Playgroud)