t8s14q
Last Updated: February 25, 2016
·
250
· ahmednaguib
E465b3eac34c18b16c7feac2045a31db

Bookmarklet to beautify json response

I had to deal with some api which returned some ugly json response so I looked for some chrome extension
to beautify the json response then I thought .. why don't I make a bookmarklet for fun to do the job for me.

/* reading the text of the page as text then parse it : */

leJson = document.body.textContent;
leJson = JSON.parse(leJson);

// clear the page content : 
 document.body.innerHTML = "";

/* Beautify the parsed json then insert it to the empty page */
document.body.appendChild(document.createTextNode(JSON.stringify(leJson, null, 4)));

// Then we need to add some css to make the  content well displayed 
var newcss = 'body { white-space: pre; font-family:  monospace; }';

// This is to add some css to the page 
if ('\v' == 'v') /* ie only */ {
    document.createStyleSheet().cssText = newcss;
} else {
    var tag = document.createElement('style');
    tag.type = 'text/css';
    document.getElementsByTagName('head')[0].appendChild(tag);
tag[(typeof document.body.style.WebkitAppearance == 'string') /* webkit only */ ? 'innerText' : 'innerHTML'] = newcss;
}

So let's make it as a bookmarklet :

 javascript: (function() {
 var newcss = "body { white-space: pre; font-family: monospace; }";
   if ('\v' == 'v') /* ie only */ {
   document.createStyleSheet().cssText = newcss;
} else {
var tag = document.createElement('style');
tag.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(tag);
tag[(typeof document.body.style.WebkitAppearance == 'string') /* webkit only */ ? 'innerText' : 'innerHTML'] = newcss;
}
leJson = document.body.textContent;
leJson = JSON.parse(leJson);
document.body.innerHTML = "";
document.body.appendChild(document.createTextNode(JSON.stringify(leJson, null, 4)))
})()

This was done quickly ... so If you have any comments or suggestions that would be awesome.

Say Thanks
Respond