Skip to content

Instantly share code, notes, and snippets.

@travist
Last active July 20, 2017 15:47
Show Gist options
  • Save travist/617e2aa49edfe371a710b1c1fc41cef8 to your computer and use it in GitHub Desktop.
Save travist/617e2aa49edfe371a710b1c1fc41cef8 to your computer and use it in GitHub Desktop.
Pretty print JSON
<pre><code id="json"></code></pre>
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;
}
var PrettyJSON = {
print: function(elementId, json) {
document.getElementById(elementId).innerHTML = PrettyJSON.prettyPrint(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, '&amp;').replace(/\\"/g, '&quot;')
.replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(jsonLine, PrettyJSON.replacer);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment