【问题标题】:How to convert bytes type to dictionary?如何将字节类型转换为字典?
【发布时间】:2018-08-17 11:35:56
【问题描述】:

我有一个这样的字节类型对象:

b"{'one': 1, 'two': 2}"

我需要使用 python 代码从中获取字典。我将其转换为字符串,然后转换为字典,如下所示。

string = dictn.decode("utf-8")
print(type(string))
>> <class 'str'>
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

【问题讨论】:

  • 无需自己制作字典解析器。将字符串发送到ast.literal_eval
  • 您在此处发布的代码不会引发该异常。事实上,它几乎可以按照您所说的去做(以处理引号字符时的一些错误为模——例如,您最终会得到一个像" 'two'" 这样的键而不是"two")。
  • 同时,这个输入是从哪里来的?将 Python dict 的 reprencode-ing 转换为 UTF-8 确实不是存储稍后要加载的数据的好方法。最好使用 JSON 或 Pickle 之类的东西。
  • @Aran-Fey 字节与字符串不同

标签: python string dictionary


【解决方案1】:

我认为还需要解码才能获得正确的字典。

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}

【讨论】:

  • 同意json.loads
【解决方案2】:

您只需要ast.literal_eval。没有什么比这更花哨的了。除非您在字符串中专门使用非 Python dict 语法,否则没有理由乱用 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))

见答案here。它还详细说明了ast.literal_evaleval 更安全。

【讨论】:

  • 似乎需要额外的解码。错误日志: raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: b"{'one': 1, 'two': 2}"
【解决方案3】:

你可以这样尝试:

import json
import ast

a= b"{'one': 1, 'two': 2}"
print(json.loads(a.decode("utf-8").replace("'",'"')))

print(ast.literal_eval(a.decode("utf-8")))

有模块的文档:

1.ast doc

2.json doc

【讨论】:

    【解决方案4】:

    您可以使用 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))
    

    【讨论】:

      猜你喜欢
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      • 1970-01-01
      • 2021-07-25
      相关资源
      最近更新 更多