Created
March 3, 2022 01:19
-
-
Save Kevin-Prichard/fb2f1f3142e0a466014e3cf040656efb to your computer and use it in GitHub Desktop.
JSON data dictionary generator: read json file, collect the key paths, write out report
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
#!/usr/bin/env node | |
//var JSON = require('JSON'); | |
var fs = require('fs'); | |
var argv = require('yargs').argv; | |
var isObject = function(v) { return v && (typeof v==='object') && !('length' in v); }; | |
var isArray = function(v) { return v && (typeof v==='object') && ('length' in v); }; | |
var isPrimitive = function(v) { var res=(typeof v in {'boolean':true,'number':true,'string':true,'undefined':true}) || (v===null); return res;}; | |
var keys = function(v) {keys=[]; for(var key in v){keys.push(key)} return keys}; | |
function getJSONKeyPaths(v, result, keyPath, superFlat) { | |
result = !result ? [] : result; | |
keyPath = !keyPath ? [] : keyPath; | |
if(isArray(v)) { | |
for(var i=0; i<v.length; i++) { | |
getJSONKeyPaths(v[i], result, keyPath.concat(superFlat ?'*' :i), superFlat); | |
} | |
} else if(isObject(v)) { | |
for(var k in v) { | |
getJSONKeyPaths(v[k], result, keyPath.concat(k), superFlat); | |
} | |
} else { | |
var endPoint = keyPath.join('.') + ' = ' + (superFlat ?typeof(v) :JSON.stringify(v)); | |
result.push(endPoint); | |
} | |
} | |
// Run from CLI (i.e. not invoked via gulp) | |
if(require.main === module) { | |
if(!argv.pathname) { | |
console.log("Usage-\n$ ./jslib/json_data_dictionary.js [--values=(true|false)] "+ | |
"--pathname=/path/to/blob.json\n Where --values=false squashes "+ | |
"key paths to the most minimal."); | |
} else { | |
var res=[]; | |
var testJSON = JSON.parse(fs.readFileSync(argv.pathname, 'utf-8')); | |
getJSONKeyPaths(testJSON, res, [], !JSON.parse(argv.values ?argv.values :'false')); | |
console.log(res.join('\n')); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment