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.
Written by ahmednaguib
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#