Skip to content

Instantly share code, notes, and snippets.

@openhoat
Created October 23, 2015 09:57
Show Gist options
  • Save openhoat/03704b22cd5b43547742 to your computer and use it in GitHub Desktop.
Save openhoat/03704b22cd5b43547742 to your computer and use it in GitHub Desktop.
Sort JSON by key
#!/usr/bin/env node
'use strict';
// Read stdin JSON, sort keys and pretty format to stdout
var stdin = process.stdin,
stdout = process.stdout,
chunks = [];
stdin.setEncoding('utf8');
stdin.on('data', chunks.push.bind(chunks));
stdin.on('end', function () {
var data, json, result;
result = {};
data = chunks.join();
json = JSON.parse(data);
if (typeof json === 'object') {
result = {};
Object.keys(json).sort().forEach(function (key) {
result[key] = json[key];
});
} else {
result = json;
}
result = JSON.stringify(result, null, 2);
stdout.write(result);
stdout.write('\n');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment