Last active
October 5, 2018 12:19
-
-
Save alex2600/fa7b51e368e210ae3093011ff234bf61 to your computer and use it in GitHub Desktop.
Sort object keys in JSON file
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 | |
/////// 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