JSON and Cryptography With Python: TypeError: Object of type bytes is not JSON serializable

JSON and Cryptography With Python: TypeError: Object of type bytes is not JSON serializable

我在这里做错了什么?我正在尝试加密用户名和密码,但是当我将它们放入 json 时,出现此错误。欢迎任何帮助!抱歉,有任何问题! Python 3.7.0 不知道密码版本

def editjson(location, value):
    with open("config.json") as f:
        data = f.read()
        d = json.loads(data)
        d[location] = [value]
        with open("config.json", 'w') as f:
            f.write(json.dumps(d))

def firstruntrue():
    key = Fernet.generate_key()
    f = Fernet(key)
    userog = input("What is your Username? ").encode()
    encrypteduser = f.encrypt(userog).decode()
    passwordog = input("What is your Password? ").encode()
    encryptedpassword = f.encrypt(passwordog).decode()
    editjson("firstrun", "False")
    editjson("user", encrypteduser)
    editjson("password", encryptedpassword)
    editjson("key", key)

with open("./config.json", "r") as handler:
    info = json.load(handler)
    user = info["user"]
    password = info["password"]
    firstrun = info["firstrun"]
C:\Users\USER\Desktop\Code>python -u C:\Users\USER\Desktop\Code\OpenGradebook.py
What is your Username? test
What is your Password? test
Traceback (most recent call last):
  File "C:\Users\USER\Desktop\Code\OpenGradebook.py", line 36, in <module>
    firstruntrue()
  File "C:\Users\USER\Desktop\Code\OpenGradebook.py", line 27, in firstruntrue
    editjson("key", key)
  File "C:\Users\USER\Desktop\Code\OpenGradebook.py", line 15, in editjson
    f.write(json.dumps(d))
  File "C:\Program Files\Python37\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Program Files\Python37\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Program Files\Python37\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Program Files\Python37\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable

来自cryptography docs

key 以字节为单位,您序列化字节对象 editjson("key", key).

试试改成editjson("key", key.decode())