Skip to content

Instantly share code, notes, and snippets.

@nash403
Created June 1, 2017 14:53
Show Gist options
  • Save nash403/b76bef21ded682fc9ce51b92901f6604 to your computer and use it in GitHub Desktop.
Save nash403/b76bef21ded682fc9ce51b92901f6604 to your computer and use it in GitHub Desktop.
Prettify JSON with JS
.string { color: #ff5722; }
.number { color: #009688; }
.boolean { color: #2196F3; }
.null { color: #3f51b5; }
.key { color: #545E6C; }
transform(value, highlight = false) {
let json = JSON.stringify(value, null, 2)
.replace(/ /g, ' ')
.replace(/\n/g, '<br/>');
if (highlight) {
// json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
} else {
return json
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment