Created
October 10, 2015 10:48
-
-
Save malash/1ebb15e23661705ed2d5 to your computer and use it in GitHub Desktop.
实现了有序的JSON格式化的AngularJS过滤器,排序使用字典序
This file contains 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
'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