Skip to content

Instantly share code, notes, and snippets.

@iolo
Created October 14, 2014 13:49
Show Gist options
  • Save iolo/c51cab5bf4ee3c6ff4fe to your computer and use it in GitHub Desktop.
Save iolo/c51cab5bf4ee3c6ff4fe to your computer and use it in GitHub Desktop.
AngularJS filter example: pretty print for json object.
angular.module('io.utils', [])
.filter('prettyJson', [function () {
return function (obj, pretty) {
if (!obj) {
return '';
}
var json = angular.toJson(obj, pretty);
if (!pretty) {
return json;
}
return json
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls;
if (/^"/.test(match)) {
cls = /:$/.test(match) ? 'key' : 'string';
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
} else {
cls = 'number';
}
return '<span class="json-' + cls + '">' + match + '</span>';
});
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment