Skip to content

Instantly share code, notes, and snippets.

@alex2600
Last active October 5, 2018 12:19
Show Gist options
  • Save alex2600/fa7b51e368e210ae3093011ff234bf61 to your computer and use it in GitHub Desktop.
Save alex2600/fa7b51e368e210ae3093011ff234bf61 to your computer and use it in GitHub Desktop.
Sort object keys in JSON file
#!/usr/bin/env node
/////// SORT OBJECT KEYS OF JSON FILE ////////////////////////////////////////////////////////////////
// TODO make recursive for object with depth > 1
/////////////////////////////////////////////////////////////////////////
const fs = require("fs")
const options = "utf8"
const file = process.argv[2]
if(!file) throw new Error("requires json file as argument")
let json = fs.readFileSync(file, options)
json = JSON.parse(json)
let keys = Object.keys(json).sort()
let ret = {}
keys.forEach(function (key) {
ret[key] = json[key]
})
let output = JSON.stringify(ret, null, " ")
// this will overwrite the source file TODO make optional
fs.writeFileSync(file, output, {encoding: options})
console.log(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment