2016-01-27 49 views
-1

我有一个表格变量返回的词典列表看起来像这样:如何解码python unicode字典列表?

share_with = u'[{\"text\":\"[email protected]\"},{\"text\":\"[email protected]\"},{\"text\":\"[email protected]\"}] 

我试图用一个列表理解获取电子邮件地址列表中,但反斜杠把它扔了。

share_with = [item for item['text'] in str(share_with)] 

但我得到的唯一错误是:

global name 'item' is not defined 

我如何环路直通的是表单变量,这样我可以得到看起来像这样的列表:

share_with = ['[email protected]','[email protected]','[email protected]'] 
+3

这不是(还)词典列表。它看起来像JSON文本;如果它是JSON,你应该使用JSON解码器。 – user2357112

+1

JSON是否允许反斜杠?如果没有,那么你可以使用https://docs.python.org/2/library/ast.html#ast.literal_eval –

回答

3

什么你有一个非常类似于JSON对象的东西。

所以,你必须将其解码为有效映射然后阅读你的电子邮件:

>>> share_with = u'[{\"text\":\"[email protected]\"},{\"text\":\"[email protected]\"},{\"text\":\"anakinskyw[email protected]\"}]' 
>>> 
>>> 
>>> import json 
>>> json.loads(share_with) 
[{'text': '[email protected]'}, {'text': '[email protected]'}, {'text': '[email protected]'}] 
>>> l = json.loads(share_with) 
>>> 
>>> l 
[{'text': '[email protected]'}, {'text': '[email protected]'}, {'text': '[email protected]'}] 
>>> 
>>> [item['text'] for item in l] 
['[email protected]', '[email protected]', '[email protected]']