Created
October 14, 2014 13:49
-
-
Save iolo/c51cab5bf4ee3c6ff4fe to your computer and use it in GitHub Desktop.
AngularJS filter example: pretty print for json object.
This file contains hidden or 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
| 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, '<') | |
| .replace(/>/g, '>') | |
| .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