Created
May 1, 2016 10:30
-
-
Save timdp/a1ef5d38b79889c082c9f4267af546ce to your computer and use it in GitHub Desktop.
Minimal JSON highlighter
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 encodeString = (function () { | |
var reReserved = /[<>&"]/g | |
var entities = { | |
'<': '<', | |
'>': '>', | |
'&': '&', | |
'"': '"' | |
} | |
var encodeEntity = function (entity) { | |
return entities[entity] | |
} | |
return function (str) { | |
return str.replace(reReserved, encodeEntity) | |
} | |
})() | |
var toHtml = function (str, type) { | |
return '<span class=\'' + type + '\'>' + encodeString(str) + '</span>' | |
} | |
var walk = function (obj) { | |
var type = (obj == null) ? 'null' | |
: Array.isArray(obj) ? 'array' | |
: typeof obj | |
if (type === 'object') { | |
for (var oldKey in obj) { | |
var newKey = toHtml(oldKey, 'key') | |
obj[newKey] = walk(obj[oldKey]) | |
delete obj[oldKey] | |
} | |
} | |
if (type === 'array') { | |
for (var i = 0; i < obj.length; ++i) { | |
obj[i] = walk(obj[i]) | |
} | |
} | |
return obj | |
} | |
var replace = function (key, obj) { | |
var type = typeof obj | |
return (type === 'object') ? obj | |
: toHtml('' + obj, 'value-' + type) | |
} | |
var highlight = function (obj) { | |
return '<pre class="json">' + | |
JSON.stringify(walk(obj), replace, 2) + | |
'</pre>' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment