Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 813
mohdnaveed Avatar asked Oct 21 '25 03:10

mohdnaveed


1 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>')
    
like image 107
ProfSmiles Avatar answered Oct 23 '25 16:10

ProfSmiles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!