Skip to main content
 首页 » 编程设计

python之将字符串从 Python3 转换为字典

2025年05月04日45mengfanrong

如何将下面的字符串从 Python3 转换为 Json?

这是我的代码:

import ast 
mystr = b'[{\'1459161763632\': \'this_is_a_test\'}, {\'1459505002853\': "{\'hello\': 12345}"}, {\'1459505708472\': "{\'world\': 98765}"}]' 
chunk = str(mystr) 
chunk = ast.literal_eval(chunk) 
print(chunk) 

从 Python2 运行我得到:

[{'1459161763632': 'this_is_a_test'}, {'1459505002853': "{'hello': 12345}"}, {'1459505708472': "{'world': 98765}"}] 

从 Python3 运行我得到:

b'[{\'1459161763632\': \'this_is_a_test\'}, {\'1459505002853\': "{\'hello\': 12345}"}, {\'1459505708472\': "{\'world\': 98765}"}]' 

如何从 Python3 运行并获得与 Python2 相同的结果?

请您参考如下方法:

mystr 中的内容是bytes 格式,只需将其解码 为ascii 然后对其求值:

>>> ast.literal_eval(mystr.decode('ascii')) 
[{'1459161763632': 'this_is_a_test'}, {'1459505002853': "{'hello': 12345}"}, {'1459505708472': "{'world': 98765}"}] 

或者在更一般的情况下,为了避免 unicode 字符出现问题,

>>> ast.literal_eval(mystr.decode('utf-8')) 
[{'1459161763632': 'this_is_a_test'}, {'1459505002853': "{'hello': 12345}"}, {'1459505708472': "{'world': 98765}"}] 

因为,默认解码方案是 utf-8,您可以从中看到:

>>> help(mystr.decode) 
Help on built-in function decode: 
 
decode(...) method of builtins.bytes instance 
    B.decode(encoding='utf-8', errors='strict') -> str 
... 

然后,您不必指定编码方案:

>>> ast.literal_eval(mystr.decode()) 
[{'1459161763632': 'this_is_a_test'}, {'1459505002853': "{'hello': 12345}"}, {'1459505708472': "{'world': 98765}"}]