Skip to content

Instantly share code, notes, and snippets.

@decodigo
Created October 8, 2014 15:43
Show Gist options
  • Save decodigo/a48f579eacba6b1465cd to your computer and use it in GitHub Desktop.
Save decodigo/a48f579eacba6b1465cd to your computer and use it in GitHub Desktop.
A Pen by Nelson Polanco.
<pre><code id=acct></code></pre>
<pre><code id=planets></code></pre>
/**
* Pretty Print JSON Objects.
* Inspired by http://jsfiddle.net/unLSJ/
*
* @return {string} html string of the formatted JS object
* @example: var obj = {"foo":"bar"}; obj.prettyPrint();
*/
Object.prototype.prettyPrint = function(){
var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
var replacer = function(match, pIndent, pKey, pVal, pEnd) {
var key = '<span class="json-key" style="color: brown">',
val = '<span class="json-value" style="color: navy">',
str = '<span class="json-string" style="color: olive">',
r = pIndent || '';
if (pKey)
r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';
if (pVal)
r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>';
return r + (pEnd || '');
};
return JSON.stringify(this, null, 3)
.replace(/&/g, '&amp;').replace(/\\"/g, '&quot;')
.replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(jsonLine, replacer);
}
var account = { active: true, codes: [48348, 28923, 39080], city: "London" };
var planets = [{ name: 'Earth', order: 3, stats: { life: true, mass: 5.9736 * Math.pow(10, 24) } }, { name: 'Saturn', order: 6, stats: { life: null, mass: 568.46 * Math.pow(10, 24) } }];
document.getElementById('acct').innerHTML = account.prettyPrint();
document.getElementById('planets').innerHTML = planets.prettyPrint();
body{
background: #efefef;
}
pre {
background-color: ghostwhite;
border: 1px solid silver;
padding: 10px 20px;
margin: 20px;
border-radius: 4px;
width: 25%;
margin-left: auto;
margin-right: auto;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment