Skip to content

Instantly share code, notes, and snippets.

@pete-rai
Created February 7, 2018 20:56
Show Gist options
  • Save pete-rai/444a4f6203869d3bcc77e9c618ab9e44 to your computer and use it in GitHub Desktop.
Save pete-rai/444a4f6203869d3bcc77e9c618ab9e44 to your computer and use it in GitHub Desktop.
A simple, concise, clean, no dependencies JSON pretty print output function
/*
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 , '&lt;' );
pretty = pretty.replace (/>/g , '&gt;' );
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