Pretty Print JSON Data in Color
by stevenkaspar
HTML
<pre><code id=account></code></pre>
<pre><code id=planets></code></pre>
CSS
pre {
background-color: ghostwhite;
border: 1px solid silver;
padding: 10px 20px;
margin: 20px;
}
.json-key {
color: brown;
}
.json-value {
color: navy;
}
.json-string {
color: olive;
}
JavaScript
if (!library)
var library = {};
library.json = {
replacer: function(match, pIndent, pKey, pVal, pEnd) {
var key = '<span class=json-key>';
var val = '<span class=json-value>';
var str = '<span class=json-string>';
var r = pIndent || '';
if (pKey)
r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';
if (pVal)
r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>';
return r + (pEnd || '');
},
prettyPrint: function(obj) {
var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
return JSON.stringify(obj, null, 3)
.replace(/&/g, '&').replace(/\\"/g, '"')
.replace(/</g, '<').replace(/>/g, '>')
.replace(jsonLine, library.json.replacer);
}
};
var account = JSON.parse("{\"id\":1855,\"lookupName\":\"Abercrombie & Fitch - Chat Implementation\",\"createdTime\":\"2016-03-03T23:42:58.000Z\",\"updatedTime\":\"2016-05-19T19:23:44.000Z\",\"accountHierarchy\":{\"links\":[{\"rel\":\"self\",\"href\":\"https://helixconsulting.custhelp.com/services/rest/connect/v1.3/opportunities/1855/accountHierarchy\"}]},\"assignedToAccount\":{\"links\":[{\"rel\":\"self\",\"href\":\"https://helixconsulting.custhelp.com/services/rest/connect/v1.3/accounts/114\"},{\"rel\":\"canonical\",\"href\":\"https://helixconsulting.custhelp.com/services/rest/connect/v1.3/accounts/114\"},{\"rel\":\"describedby\",\"href\":\"https://helixconsulting.custhelp.com/services/rest/connect/v1.3/metadata-catalog/accounts\"}]},\"banner\":{\"importanceFlag\":null,\"text\":null,\"updatedByAccount\":null,\"updatedTime\":null},\"closedTime\":\"2016-05-18T21:11:34.000Z\",\"closedValue\":{\"currency\":null,\"exchangeRate\":{\"id\":1,\"lookupName\":\"01/03/1970 -...