Skip to content

Instantly share code, notes, and snippets.

@timdp
Created May 1, 2016 10:30
Show Gist options
  • Save timdp/a1ef5d38b79889c082c9f4267af546ce to your computer and use it in GitHub Desktop.
Save timdp/a1ef5d38b79889c082c9f4267af546ce to your computer and use it in GitHub Desktop.
Minimal JSON highlighter
var encodeString = (function () {
var reReserved = /[<>&"]/g
var entities = {
'<': '&lt;',
'>': '&gt;',
'&': '&amp;',
'"': '&quot;'
}
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