1
0
mirror of synced 2025-12-18 21:01:34 +08:00

add option to sort object keys

This commit is contained in:
Zach Carter
2011-06-01 17:54:36 -04:00
parent 7d7e4b499f
commit f08f1b245f

View File

@@ -17,6 +17,10 @@ var options = require("nomnom")
return JSON.parse(fs.readFileSync(__dirname + "/../package.json", "utf8")).version; return JSON.parse(fs.readFileSync(__dirname + "/../package.json", "utf8")).version;
} }
}, },
sort : {
string: '-s, --sort-keys',
help: 'sort object keys'
},
inplace : { inplace : {
string: '-i, --in-place', string: '-i, --in-place',
help: 'overwrite the file' help: 'overwrite the file'
@@ -32,7 +36,10 @@ var options = require("nomnom")
function parse (source) { function parse (source) {
try { try {
return JSON.stringify(parser.parse(source),null,options.indent); var parsed = options.sort ?
sortObject(parser.parse(source)) :
parser.parse(source);
return JSON.stringify(parsed,null,options.indent);
} catch (e) { } catch (e) {
sys.puts(e); sys.puts(e);
process.exit(1); process.exit(1);
@@ -47,7 +54,7 @@ function main (args) {
if (options.inplace) { if (options.inplace) {
fs.writeSync(fs.openSync(path,'w+'), parse(source), 0, "utf8"); fs.writeSync(fs.openSync(path,'w+'), parse(source), 0, "utf8");
} else { } else {
sys.pupts(parse(source)); sys.puts(parse(source));
} }
} else { } else {
var stdin = process.openStdin(); var stdin = process.openStdin();
@@ -62,4 +69,25 @@ function main (args) {
} }
} }
// from http://stackoverflow.com/questions/1359761/sorting-a-json-object-in-javascript
function sortObject(o) {
if (Object.prototype.toString.call(o) != '[object Object]')
return o;
var sorted = {},
key, a = [];
for (key in o) {
if (o.hasOwnProperty(key)) {
a.push(key);
}
}
a.sort();
for (key = 0; key < a.length; key++) {
sorted[a[key]] = sortObject(o[a[key]]);
}
return sorted;
}
main(process.argv.slice(1)); main(process.argv.slice(1));