Created
May 27, 2016 13:05
-
-
Save danielbuechele/9dcece167dbec1a01b7098ba090e6a9b to your computer and use it in GitHub Desktop.
Convert DIGAS .DBE filte to JSON
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
var fs = require('fs'); | |
const keyRegex = /(\[[A-Z\/#0-9]+\])/; | |
if (process.argv.length < 3) { | |
console.error('No file name given.'); | |
process.exit(1); | |
} else { | |
parse(process.argv[2]).then(o => { | |
console.log(o); | |
}); | |
} | |
function parse(filename) { | |
return new Promise((resolve, reject) => { | |
fs.readFile(filename, {encoding: 'binary'}, function (err, data) { | |
console.log(err, data); | |
if (err) reject(err); | |
const o = {}; | |
const items = data.split(keyRegex); | |
for (let i = 1; i < items.length; i += 2) { | |
if (keyRegex.test(items[i]) && !keyRegex.test(items[i+1])) { | |
let key = items[i].substr(1, items[i].length-2).toLowerCase(); | |
if (key.indexOf('/') === -1) { | |
o[key] = getValue(items[i+1]); | |
} else { | |
let keypath = key.split('/'); | |
let ref = o; | |
for (let j = 0; j < keypath.length; j++) { | |
if (j === keypath.length-1) { | |
ref[keypath[j]] = getValue(items[i+1]); | |
} else { | |
ref[keypath[j]] = ref[keypath[j]] || {}; | |
ref = ref[keypath[j]]; | |
} | |
} | |
} | |
} | |
} | |
resolve(arraify(o)); | |
}); | |
}); | |
} | |
function arraify(o) { | |
if (o instanceof Array) { | |
o.forEach(k => { | |
o[k] = arraify(o[k]); | |
}); | |
} else if (typeof o === 'object') { | |
Object.keys(o).forEach(k => { | |
if (typeof o[k] === 'object' && Object.keys(o[k])[0] && Object.keys(o[k])[0].indexOf('#') > -1) { | |
o[k] = Object.keys(o[k]).map(j => o[k][j]); | |
} else { | |
o[k] = arraify(o[k]); | |
} | |
}); | |
} | |
return o; | |
} | |
function getValue(val) { | |
if (/^-?\d+$/.test(val)) { | |
return parseInt(val); | |
} else if (/^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}$/.test(val)) { | |
const match = val.match(/^(\d+)-(\d+)-(\d+) (\d+)\:(\d+)\:(\d+)$/); | |
return new Date(match[1], match[2] - 1, match[3], match[4], match[5], match[6]); | |
} else if (/^\d{4}-\d{2}-\d{2}$/.test(val)) { | |
return new Date(val); | |
} else { | |
return val; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment