Created
October 23, 2015 09:57
-
-
Save openhoat/03704b22cd5b43547742 to your computer and use it in GitHub Desktop.
Sort JSON by key
This file contains hidden or 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
#!/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