Pretty Print JSON with JavaScript
An updated example based on this StackOverflow answer (http://stackoverflow.com/a/7220510/102401)
by neonDog
HTML
<pre id="pretty_json"></pre>
CSS
body {
background: #222;
color: #0
}
JavaScript
// Takes a JSON object, returns a pretty printed and syntax highlighted
function jsonPrettyHighlightToId(jsonobj, id_to_send_to) {
var json = JSON.stringify(jsonobj, undefined, 2);
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
json = json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'color: darkorange;';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'color: red;';
} else {
cls = 'color: green;';
}
} else if (/true|false/.test(match)) {
cls = 'color: blue;';
} else if (/null/.test(match)) {
cls = 'color: magenta;';
}
return '<span style="' + cls + '">' + match + '</span>';
});
document.getElementById(id_to_send_to).innerHTML = json;
}
// Example
var obj = {a:1, 'b':'foo', c:[true,false,null,'true','false','null', {d:{e:1.3e5,f:'1.3e5'}}]};
jsonPrettyHighlightToId(obj, 'pretty_json');