Skip to content

Instantly share code, notes, and snippets.

@malash
Created October 10, 2015 10:48
Show Gist options
  • Save malash/1ebb15e23661705ed2d5 to your computer and use it in GitHub Desktop.
Save malash/1ebb15e23661705ed2d5 to your computer and use it in GitHub Desktop.
实现了有序的JSON格式化的AngularJS过滤器,排序使用字典序
'use strict';
angular.module('metrics').filter('orderedJson', [
function () {
return function (data) {
function _json(d) {
var ret = '';
var k;
var value;
if (!angular.isObject(d) && !angular.isArray(d)) {
return JSON.stringify(d);
} else if (angular.isArray(d)) {
for (k in d) {
ret += (ret === '') ? '[' : ',';
ret += _json(d[k]);
}
return ret + ']';
} else if (angular.isObject(d)) {
var keys = [];
for (k in d) {
keys.push(k);
}
keys = keys.sort();
keys.forEach(function(k) {
ret += (ret === '') ? '{' : ',';
value = _json(d[k]);
if (!angular.isDefined(value)) {
return;
}
ret += '"' + k.toString() + '":' + value;
});
return ret + '}';
}
}
return _json(data);
};
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment