Last active
July 11, 2017 11:06
-
-
Save sujeetkv/d4ffc747b8f8024559fff20999b3e0ec to your computer and use it in GitHub Desktop.
JSON Prettify
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
/** | |
* 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, '&').replace(/</g, '<').replace(/>/g, '>'); | |
} 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; | |
}; |
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
//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