Reputation: 13
I'm appending multiple dictionaries to a list and then converting the same to json. Its giving me multiple lists with each list adding one extra result. I want to display entire output in a single array of list.
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))
The output I'm getting:
[
{
"Body": "Forwarded.\r\n\r\nFrom: User
"Subject": "Fw: Tuesday",
"To": "<[email protected]>"
}
]
[
{
"Body": "Forwarded.\r\n\r\nFrom: User
"Subject": "Fw: Tuesday",
"To": "<[email protected]>"
},
{
"Body": "Urgent Message.\r\n\r\nFrom: Alerts
"Subject": "Alerts",
"To": "<[email protected]>"
}
]
Output expected:
[
{
"Body": "Forwarded.\r\n\r\nFrom: User
"Subject": "Fw: Tuesday",
"To": "<[email protected]>"
},
{
"Body": "Urgent Message.\r\n\r\nFrom: Alerts
"Subject": "Alerts",
"To": "<[email protected]>"
}
.....
]
Upvotes: 1
Views: 135
Reputation: 1215
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))
You just have an issue with indentation.. see the last line here.. it's the only part I changed. Otherwise the script will print for each iteration of for i in mail_ids.split()
.
Upvotes: 1