How to send a json object pretty printed as an email python

Question:

I have a python script that gets a cluster health as json and sends me a mail. The issue is that the json is not pretty printed.
These are the methods I have tried already:

  1. Simple –> json.dumps(health)
  2. json.dumps(health, indent=4, sort_keys=True)

But the output in gmail is still unformatted, somewhat like this

{ "active_primary_shards": 25, "active_shards": 50, "active_shards_percent_as_number": 100.0, "cluster_name": "number_of_pending_tasks": 0, "relocating_shards": 0, "status": "green", "task_max_waiting_in_queue_millis": 0, "timed_out": false, "unassigned_shards": 0 }

Mail was sent to gmail

Asked By: mohdnaveed

||

Answers:

I can’t say for certain, but it would seem like your email-sending code is defaulting to sending an “HTML” email, and in HTML consecutive spaces collapse into one, that way HTML code like:

<p>
    This is a paragraph, but it's long so
    I'll break to a new line, and indented
    so I know it's within the `p` tag, etc.
</p>

Looks like “This is a paragraph, but it’s long so I’ll break to a new line, and indented so I know it’s within the p tag, etc.” to the user.

So, I’d say your two options are:

  1. Change the email sending code to send the Content-type header as text/plain, or
  2. Replace all your spaces with the &nbsp; (non-breaking space) character and newlines with <br> (breaks), for example:

    email_body = json.dumps(
        health, indent=4, sort_keys=True).replace(' ', '&nbsp;').replace('n', '<br>')
    
Answered By: Grace B
>>> import json
>>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
>>> print s
{
    "4": 5, 
    "6": 7
}

mine works fine
Python 2.7.3 (default, Jan 17 2015, 17:10:37)
[GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2

maybe it’s version related, post your version and output

Answered By: jack

The suggested solutions did not work for me. I tried json pretty printed into a variable and I see the email with expected json pretty format.

import json, pprint
body=json.dumps(message, indent=4) 
pprint.pformat(body, indent=4) # pprint body but assign the output to body variable instead of printing to console. This will introduce new line and other expected characters in the message string body. 
body=body.replace("n","<br/>") # I just replaced new line with <br/>
message = MIMEText(body, "HTML") # create an MIME message and send the body to intented email recepient.
Answered By: Vishal
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.