【问题标题】:"TypeError: Object of type bytes is not JSON serializable"“TypeError:字节类型的对象不是 JSON 可序列化的”
【发布时间】:2019-05-22 20:21:56
【问题描述】:

试图在 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...")

我希望程序保存游戏数据的文件,但它只返回“TypeError: a bytes-like object is required, not 'str'”错误

我认为这与我在 encrypt_dict 函数中对变量进行编码有关,但我不确定,我浏览过与此类似的其他问题,但没有找到任何可以解决我的错误的问题

【问题讨论】:

  • 哪一行报错?

标签: python json python-3.x encoding byte


【解决方案1】:

问题是encrypt_dict 中的base64.b64encode(bytes(fk, 'utf-8')) 返回一个字节字符串(b'NGtUbnNEc2hXZTlsOE1tcWVoVkNOUjMtWVIxcVZrWGV1WlBVcjJ2WkhHST0='),而 encrypt_string 返回一个普通字符串(没有前导 b)。 JSON 格式仅支持 unicode 字符串。

这可以通过用

替换 encrypt_dict 中的第 16 行来解决
ed['fk'] = base64.b64encode(bytes(fk, 'utf-8')).decode("ascii")

【讨论】:

    猜你喜欢
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    • 2021-03-11
    • 2019-11-21
    • 2021-11-13
    相关资源
    最近更新 更多