Created
February 7, 2018 20:56
-
-
Save pete-rai/444a4f6203869d3bcc77e9c618ab9e44 to your computer and use it in GitHub Desktop.
A simple, concise, clean, no dependencies JSON pretty print output function
This file contains 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
/* | |
use the following in your css file | |
.json-key { color: red; } | |
.json-value { color: blue; } | |
.json-string { color: green; } | |
set your output like this: | |
$('#output').html (prettyPrint (myjson)); | |
*/ | |
function prettyPrint (json) | |
{ | |
var line = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg; | |
var pretty = JSON.stringify (json, null, 3); | |
pretty = pretty.replace (/&/g , '&' ); | |
pretty = pretty.replace (/\\"/g, '"'); | |
pretty = pretty.replace (/</g , '<' ); | |
pretty = pretty.replace (/>/g , '>' ); | |
pretty = pretty.replace (line, function (match, indent, key, val, end) | |
{ | |
var akey = '<span class=json-key>'; | |
var aval = '<span class=json-value>'; | |
var astr = '<span class=json-string>'; | |
var text = indent || ''; | |
if (key) | |
{ | |
text = text + akey + key.replace (/[": ]/g, '') + '</span>: '; | |
} | |
if (val) | |
{ | |
text = text + (val [0] == '"' ? astr : aval) + val + '</span>'; | |
} | |
return text + (end || ''); | |
}); | |
return pretty; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment