簡體   English   中英

將字符串從Python3轉換為dict

[英]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相同的結果?

mystrbytes格式,只需decodedecodeascii ,然后對其進行評估:

>>> 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM