如何将以下字符串从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/