user2727195
user2727195

Reputation: 7330

Formatting JSON for email body

I've JSON in the following format that I'm trying to insert into outlook/email client's body using

location.href = "mailto:" + "[email protected]" + "?subject=" + "Notes" + "&body=" + JSON.stringify(data, null, 4);

Giving 4 spaces JSON.stringify(data, null, 4)

[
    {
        "page": "article_0_page_0",
        "note": "Note 1"
    },
    {
        "page": "article_0_page_1",
        "note": "Note 2"
    }
]

I want to output as

<b>article_0_page_0</b>\n\r
Note 1

<b>article_0_page_1</b>\n\r
Note 2

Any regular expression solution please.

Edit: My attempt

var str = "";
        for(var i=0; i<data.length; i++) {
            str += "<strong>" + data[i].page + "</strong><br>" + data[i].note + "<br><br>";
        }

Upvotes: 3

Views: 21945

Answers (3)

PotatoFarmer
PotatoFarmer

Reputation: 2974

This is what I used to convert basic JSON to "readable" for email:

let json = {
  "key": "asdas",
  "query": "",
  "hints": {
    "nested1": "blahblah"
  }
}

let prettyJSON = JSON.stringify(json, null, '&nbsp;')
  .split('\n')
  .join('<br>&nbsp;&nbsp;')
  .split('<br>&nbsp;&nbsp;}').join('<br>}')

document.body.innerHTML += `<div>${prettyJSON}</div>`

Upvotes: 1

Michael Warner
Michael Warner

Reputation: 4237

I think the above answer is ok if you have a flat structure.

If you want a more holistic approach for email specifically, I have found this to work really well.

const data = {...}
JSON.stringify( data, null, '&nbsp;' ).split( '\n' ).join( '<br>' );

This will convert something like this

const json = {
  "status": "ok",
   "config": {
     "gotIt": "yes",
     "transform": [
       null
     ]
   }
}

Into something like this

{<br>&nbsp"status": "ok",<br>&nbsp"config": {<br>&nbsp&nbsp"gotIt": "yes",<br>&nbsp&nbsp"transform": [<br>&nbsp&nbsp&nbspnull<br>&nbsp&nbsp]<br>&nbsp}<br>}

Email clients will render this as the following

{
 "status": "ok",
 "config": {
  "gotIt": "yes",
  "transform": [
   null
  ]
 }
}

This is done by using the additional parameters in JSON.stringify which I don't see used very often if you want to read more about these parameters here is the link for them.

Upvotes: 10

aknatn
aknatn

Reputation: 673

Here ya go

var json = [
    {
        "page": "article_0_page_0",
        "note": "Note 1"
    },
    {
        "page": "article_0_page_1",
        "note": "Note 2"
    }
];

var out = "";

for (var key in json) {
  if (json.hasOwnProperty(key)) {
      out += "<b>"+json[key].page+"</b>\r\n"+json[key].note+"\r\n\r\n";
  }
}

console.log(out);

Example Here: https://jsfiddle.net/q5r4gdcn/1/

Upvotes: 6

Related Questions