我有一个像这样的 bytes 类型对象:
b"{'one': 1, 'two': 2}"
我需要使用Python代码从上述字节类型对象中获取正确的Python字典。
string = b"{'one': 1, 'two': 2}"
d = dict(toks.split(":") for toks in string.split(",") if toks)
但是我收到以下错误:
------> d = dict(toks.split(":") for toks in string.split(",") if toks)
TypeError: 'bytes' object is not callable
我认为还需要解码才能获得正确的字典。
a= b"{'one': 1, 'two': 2}"
ast.literal_eval(a.decode('utf-8'))
**Output:** {'one': 1, 'two': 2}
接受的答案产生
a= b"{'one': 1, 'two': 2}"
ast.literal_eval(repr(a))
**output:** b"{'one': 1, 'two': 2}"
literal_eval 没有正确地处理我的许多代码,所以我个人更喜欢使用 json 模块来实现这一点
import json
a= b"{'one': 1, 'two': 2}"
json.loads(a.decode('utf-8'))
**Output:** {'one': 1, 'two': 2}
您所需要的只是
ast.literal_eval
。没有什么比这更奇特的了。除非您在字符串中专门使用非 Python 字典语法,否则没有理由搞乱 JSON。
# python3
import ast
byte_str = b"{'one': 1, 'two': 2}"
dict_str = byte_str.decode("UTF-8")
mydata = ast.literal_eval(dict_str)
print(repr(mydata))
请参阅答案此处。它还详细说明了
ast.literal_eval
如何比eval
更安全。
您可以使用 Base64 库将字符串字典转换为字节,尽管您可以使用 json 库将字节结果转换为字典。尝试下面的示例代码。
import base64
import json
input_dict = {'var1' : 0, 'var2' : 'some string', 'var1' : ['listitem1','listitem2',5]}
message = str(input_dict)
ascii_message = message.encode('ascii')
output_byte = base64.b64encode(ascii_message)
msg_bytes = base64.b64decode(output_byte)
ascii_msg = msg_bytes.decode('ascii')
# Json library convert stirng dictionary to real dictionary type.
# Double quotes is standard format for json
ascii_msg = ascii_msg.replace("'", "\"")
output_dict = json.loads(ascii_msg) # convert string dictionary to dict format
# Show the input and output
print("input_dict:", input_dict, type(input_dict))
print()
print("base64:", output_byte, type(output_byte))
print()
print("output_dict:", output_dict, type(output_dict))
简单😁
data = eval(b"{'one': 1, 'two': 2}")