Last active
July 20, 2017 15:47
-
-
Save travist/617e2aa49edfe371a710b1c1fc41cef8 to your computer and use it in GitHub Desktop.
Pretty print JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<pre><code id="json"></code></pre> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, '&').replace(/\\"/g, '"') | |
.replace(/</g, '<').replace(/>/g, '>') | |
.replace(jsonLine, PrettyJSON.replacer); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment