How to easily beautify JSON code in a webpage

08 Jul 2012

I had the need to beautify some dumps that I was copying into an html page. I could’ve converted online by using one of the many tools available out there, such as

But I went for the “do it yourself” way, and came out with a simple snipped of code that can beautify the some parts of the page. In my case, those blocks are inside tags. As not all the code tags do contain JSON, I wrap the parsing in a try-catch block.

<script>
window.addEventListener('load', function(){
    var codeblocks = document.getElementsByTagName('code');
    for (i in codeblocks) {
        try {
            var dirty = codeblocks[i].innerHTML;
            var clean = JSON.stringify(JSON.parse(dirty), null, 2);
            codeblocks[i].innerHTML = clean;
        }catch(e){
            //The block didn't have any JSON
        }
    };
});
</script>