Skip to content

Instantly share code, notes, and snippets.

@sujeetkv
Last active July 11, 2017 11:06
Show Gist options
  • Save sujeetkv/d4ffc747b8f8024559fff20999b3e0ec to your computer and use it in GitHub Desktop.
Save sujeetkv/d4ffc747b8f8024559fff20999b3e0ec to your computer and use it in GitHub Desktop.
JSON Prettify
/**
* jsonPrettify
*
* @param {String|Object} json Json object or string
* @param {Boolean} preformatted Preformatted for html
* @param {Boolean} colored Colored for preformatted
*
* @return {String}
*/
var jsonPrettify = function (json, preformatted, colored) {
var jsonObj = (typeof json === 'string') ? JSON.parse(json) : json;
var jsonStr = JSON.stringify(jsonObj, null, 4);
var preOpen = '';
var preClose = '';
if (preformatted) {
preOpen = '<pre>';
preClose = '</pre>';
jsonStr = jsonStr.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
} else {
colored = false;
}
if (!colored) {
return preOpen + jsonStr + preClose;
}
return preOpen + jsonStr.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var color = 'darkorange';//number
if (/^"/.test(match)) {
if (/:$/.test(match)) {
color = 'red';// key
} else {
color = 'green';// string
}
} else if (/true|false/.test(match)) {
color = 'blue';// boolean
} else if (/null/.test(match)) {
color = 'magenta';// null
}
return '<span style="color: '+ color +';">' + match + '</span>';
}) + preClose;
};
//from object
var prettyJson = jsonPrettify({a: 1, 'b': 'foo', c: [false, 'false', null, 'null', {d: {e: 1.3e5, f: '1.3e5'}}]});
//from string
var prettyJson = jsonPrettify('{"fname":"Sujeet", "lname":"Kumar"}');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment