Skip to content

Instantly share code, notes, and snippets.

@jcayzac
Created April 6, 2012 10:38
Show Gist options
  • Save jcayzac/2318775 to your computer and use it in GitHub Desktop.
Save jcayzac/2318775 to your computer and use it in GitHub Desktop.
var sortedJSON = function (obj) {
if (obj === null) {
return 'null';
}
if (Array.isArray(obj)) {
return '[' + obj.map(sortedJSON).join(',') + ']';
}
if (obj instanceof RegExp) {
return sortedJSON(obj.source);
}
if (typeof obj === "object" && !(obj instanceof Date)) {
return '{' + Object.keys(obj).sort().map(function (key) {
return [key, sortedJSON(obj[key])];
}).filter(function (tuple) {
return typeof tuple[1] !== "undefined";
}).map(function (tuple) {
return '"' + tuple[0] + '": ' + tuple[1];
}).join(', ') + '}';
}
return JSON.stringify(obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment