Skip to content

Instantly share code, notes, and snippets.

@michaelBenin
Created March 2, 2014 05:41
Show Gist options
  • Save michaelBenin/9302474 to your computer and use it in GitHub Desktop.
Save michaelBenin/9302474 to your computer and use it in GitHub Desktop.
Alphabetize your json file
# python alphabetize-json test.json
import json
import sys
args = sys.argv[1:]
for json_file in args:
with open(json_file, 'r') as file:
alphabetized = json.loads(file.read())
with open(json_file, 'w') as w:
w.write(json.dumps(alphabetized, separators=(',', ': '), indent=2, sort_keys=True))
w.close()
@jfhbrook
Copy link

jfhbrook commented Mar 6, 2014

var fs = require('fs');

function sortedKeys(input) {
  var output = {};

  // Depends on keys showing in order of definition
  // I don't think ecma specifies this behavior but I've
  // never seen this expectation violated.
  Object.keys(input).sort().forEach(function(k) {
    output[k] = input[k];
  });
  return output;
};

var f = process.argv.pop();

fs.writeFileSync(f, JSON.stringify(sortedKeys(JSON.parse(fs.readFileSync(f)))));

@michael-benin-CN
Copy link

@michaelBenin
Copy link
Author

FYI ^ didn't cut it for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment