Last active
January 27, 2017 19:35
-
-
Save bhenderson/5c930fd5749098b3ed2c5d55db30995c to your computer and use it in GitHub Desktop.
json pretty printer
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
javascript:( | |
function (){ | |
var json = JSON.parse(document.body.innerText); | |
var create = function(el, props) { | |
var e = document.createElement(el); | |
if (props) { | |
Object.keys(props).forEach(function(key) { | |
e[key] = props[key]; | |
}); | |
} | |
e.inner_text = function(obj) { | |
return e.inner(document.createTextNode(obj)); | |
}; | |
e.inner = function(obj) { | |
e.appendChild(obj); | |
return e; | |
}; | |
return e; | |
}; | |
var parse = function(obj, klass) { | |
var data; | |
if (Array.isArray(obj)) { | |
data = create("span"); | |
data.inner_text("["); | |
obj.forEach(function(val, idx) { | |
var div = create("div"); | |
div.inner(parse(val)); | |
if (idx !== obj.length-1) { | |
div.inner_text(","); | |
} | |
data.inner(div); | |
}); | |
data.inner_text("]"); | |
return data; | |
} | |
if (typeof obj === "object" && obj !== null) { | |
var keys = Object.keys(obj); | |
data = create("span"); | |
data.inner_text("{"); | |
keys.forEach(function(key, idx) { | |
var val = obj[key]; | |
var div = create("div"); | |
div.inner(parse(key, "key")); | |
div.inner_text(": "); | |
div.inner(parse(val)); | |
if (idx !== keys.length-1) { | |
div.inner_text(","); | |
} | |
data.inner(div); | |
}); | |
data.inner_text("}"); | |
return data; | |
} | |
if (!klass) { | |
switch (typeof obj) { | |
case "boolean": | |
klass = "boolean"; | |
break; | |
case "string": | |
klass = "string"; | |
if (obj.match("^https?://")) { | |
var span = create("span", {className: klass}); | |
span.inner_text('"'); | |
span.inner(create("a", {className: klass, href: obj}).inner_text(obj)); | |
span.inner_text('"'); | |
return span; | |
} | |
break; | |
case "number": | |
klass = "number"; | |
break; | |
case "object": | |
klass = "isnull"; | |
break; | |
} | |
} | |
return create("span", {className: klass}).inner_text(JSON.stringify(obj)); | |
}; | |
document.head.innerHTML = "" + | |
" <style> " + | |
" div { " + | |
" margin-left: 26px; " + | |
" } " + | |
" .boolean { " + | |
" color: red; " + | |
" } " + | |
" .string { " + | |
" color: green; " + | |
" } " + | |
" .number { " + | |
" color: blue; " + | |
" } " + | |
" .isnull { " + | |
" color: gray; " + | |
" } " + | |
" </style> " + | |
""; | |
window.json = json; | |
var data = parse(json); | |
document.body.innerHTML = ""; | |
document.body.appendChild(data); | |
} | |
)() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment