Last active
June 1, 2017 13:30
-
-
Save Juszczak/4a1540a676f6a227e898d42e56379fe8 to your computer and use it in GitHub Desktop.
dirty `.json` <-> `.properties` converter
This file contains 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
const fs = require('fs') | |
const path = require('path') | |
const PROPS_DELIMITER = '=' | |
const readJSON = fileName => JSON.parse(fs.readFileSync(path.resolve(process.cwd(), fileName), 'utf8')) | |
const toJSON = data => { | |
const output = {} | |
data.split('\n') | |
.filter(line => !!line) | |
.forEach(line => { | |
const keyVal = line.split(PROPS_DELIMITER) | |
output[keyVal[0]] = keyVal[1]; | |
}) | |
return output; | |
} | |
const readJProperties = fileName => toJSON(fs.readFileSync(path.resolve(process.cwd(), fileName), 'utf8')) | |
const unflatten = (data) => { | |
if (Object(data) !== data || Array.isArray(data)) | |
return data; | |
var regex = /\.?([^.\[\]]+)|\[(\d+)\]/g, resultholder = {}; | |
for (var p in data) { | |
var cur = resultholder, prop = '', m; | |
while (m = regex.exec(p)) { | |
cur = cur[prop] || (cur[prop] = (m[2] ? [] : {})); | |
prop = m[2] || m[1]; | |
} | |
cur[prop] = data[p]; | |
} | |
return resultholder[''] || resultholder; | |
}; | |
const flatten = (data) => { | |
let result = {}; | |
function recurse(cur, prop) { | |
if (Object(cur) !== cur) { | |
result[prop] = cur; | |
} else if (Array.isArray(cur)) { | |
for (var i = 0, l = cur.length; i < l; i++) | |
recurse(cur[i], prop + '[' + i + ']'); | |
if (l == 0) | |
result[prop] = []; | |
} else { | |
var isEmpty = true; | |
for (var p in cur) { | |
isEmpty = false; | |
recurse(cur[p], prop ? prop + '.' + p : p); | |
} | |
if (isEmpty && prop) | |
result[prop] = {}; | |
} | |
} | |
recurse(data, ''); | |
return result; | |
} | |
const writeFlat = (data) => | |
fs.writeFileSync('locale.properties', data) | |
const toJProperties = (flat) => { | |
let output = ''; | |
Object.keys(flat).forEach((key) => { | |
output += `${key}${PROPS_DELIMITER}${flat[key]}\n`; | |
}); | |
return output; | |
} | |
const inputName = process.argv[2] | |
const outputName = process.argv[3] | |
if (!inputName || !outputName) { | |
console.log('specify input and output filenames') | |
} | |
const jsonToProperties = () => | |
fs.writeFileSync(outputName, toJProperties(flatten(readJSON(inputName)))) | |
const propertiesToJson = () => | |
fs.writeFileSync(outputName, JSON.stringify(unflatten(readJProperties(inputName)))) | |
const flow = /\.json$/.test(inputName) | |
? jsonToProperties | |
: propertiesToJson | |
flow() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment