我要将多个字典添加到列表中,然后将其转换为json。它给了我多个列表,每个列表增加了一个额外的结果。我想将整个输出显示在列表的单个数组中。
mail_output = []
for i in mail_ids.split():
result, msg_data = mail.fetch(i, '(RFC822)')
for each_response in msg_data:
if isinstance(each_response, tuple):
msg = email.message_from_string(each_response[1])
items_list = msg.items()
dict_items = OrderedDict(items_list)
email_body = ''
if msg.is_multipart():
for part in msg.walk():
case...
dict_items.update({'Body': email_body})
mail_output.append(dict_items)
print(json.dumps(mail_output, indent=4, sort_keys=True))
我得到的输出:
[
{
"Body": "Forwarded.\r\n\r\nFrom: User
"Subject": "Fw: Tuesday",
"To": "<reciever@gmail.com>"
}
]
[
{
"Body": "Forwarded.\r\n\r\nFrom: User
"Subject": "Fw: Tuesday",
"To": "<reciever@gmail.com>"
},
{
"Body": "Urgent Message.\r\n\r\nFrom: Alerts
"Subject": "Alerts",
"To": "<reciever@gmail.com>"
}
]
预期输出:
[
{
"Body": "Forwarded.\r\n\r\nFrom: User
"Subject": "Fw: Tuesday",
"To": "<reciever@gmail.com>"
},
{
"Body": "Urgent Message.\r\n\r\nFrom: Alerts
"Subject": "Alerts",
"To": "<reciever@gmail.com>"
}
.....
]
答案 0 :(得分:1)
mail_output = []
for i in mail_ids.split():
result, msg_data = mail.fetch(i, '(RFC822)')
for each_response in msg_data:
if isinstance(each_response, tuple):
msg = email.message_from_string(each_response[1])
items_list = msg.items()
dict_items = OrderedDict(items_list)
email_body = ''
if msg.is_multipart():
for part in msg.walk():
case...
dict_items.update({'Body': email_body})
mail_output.append(dict_items)
print(json.dumps(mail_output, indent=4, sort_keys=True))
您只是遇到缩进问题。.请参阅此处的最后一行..这是我更改的唯一部分。否则,脚本将为for i in mail_ids.split()
的每次迭代打印。