Last active
February 1, 2018 11:18
-
-
Save rnarian/90450783180b1287842fa3b380fe1675 to your computer and use it in GitHub Desktop.
Simple node script which turns serialized keys in json files into nested json objects
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
/** | |
* | |
* Simple node script which turns serialized keys | |
* in json file into nested json object | |
* | |
* input: { | |
* "key.key2": "value" | |
* } | |
* | |
* output: { | |
* "key" { | |
* "key2": "value" | |
* } | |
* } | |
* | |
**/ | |
var file = require('./input/en.json'), | |
fs = require('fs'), | |
unflatten = require('flat').unflatten; | |
function sortObject(object){ | |
var sortedObj = {}, | |
keys = Object.keys(object); | |
keys.sort(function(key1, key2){ | |
key1 = key1.toLowerCase(), key2 = key2.toLowerCase(); | |
if(key1 < key2) return -1; | |
if(key1 > key2) return 1; | |
return 0; | |
}); | |
for(var index in keys){ | |
var key = keys[index]; | |
if(typeof object[key] == 'object' && !(object[key] instanceof Array)){ | |
sortedObj[key] = sortObject(object[key]); | |
} else { | |
sortedObj[key] = object[key]; | |
} | |
} | |
return sortedObj; | |
} | |
var unflat = unflatten(file); | |
var unflatFile = JSON.stringify(sortObject(unflat), null, 4); | |
fs.writeFile("./output/en.json", unflatFile, function(err) { | |
if(err) { | |
return console.log(err); | |
} | |
console.log("The file was saved!"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment