如何将以下字符串从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格式,只需将decode转换为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}"}]

关于python - 将字符串从Python3转换为dict,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36354184/

10-10 23:47