Makes JSON objects a lot easier to read. Great for debugging.
A Pen by Nelson Polanco on CodePen.
<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, '&').replace(/\\"/g, '"') | |
.replace(/</g, '<').replace(/>/g, '>') | |
.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(); | |
Makes JSON objects a lot easier to read. Great for debugging.
A Pen by Nelson Polanco on CodePen.
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; | |
} | |