将字符串从Python3转换为dict

时间:2016-04-01 10:38:20

标签: python python-2.7 python-3.x

如何将此字符串从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相同的结果?

2 个答案:

答案 0 :(得分:3)

mystr中的内容为bytes格式,decodeascii,然后对其进行评估:

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

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

>>> 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}"}]

答案 1 :(得分:2)

Iron Fist打败了我。为了扩展他的答案,字符串上的'b'前缀表示(对python3而不是python2)文字应该被解释为字节序列,而不是字符串。

结果是需要.decode方法将字节转换回字符串。 Python2没有对字节和字符串进行区分,因此存在差异。

有关详细信息,请参阅What does the 'b' character do in front of a string literal?