[英]Converting string from Python3 to dict
如何將下面的字符串從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
其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}"}]
鐵拳擊敗了我。 為了擴展他的答案,字符串上的'b'前綴指示(對python3而不是python2)指示文字應解釋為字節序列,而不是字符串。
結果是需要使用.decode方法將字節轉換回字符串。 Python2沒有在字節和字符串之間進行區分,因此有所不同。
請參見字符串文字前的'b'字符做什么? 有關更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.