Socket
Socket
Sign inDemoInstall

json2bash

Package Overview
Dependencies
Maintainers
1
Versions
32
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

json2bash - npm Package Compare versions

Comparing version 0.0.3 to 0.2.0

_stdin_data.txt

469

json2bash.js

@@ -12,137 +12,394 @@ #!/usr/bin/env node

//add --help as first args if no argument is given and we are not in a pipeline
var pipeMode = process.stdin._readableState.sync;
//process.stdin.isTTY || process.stdin.isTTY==false? true:false;
//console.log(pipeMode);
if ((!args || args.length == 0 || args[0] == "--help")
&& pipeMode == false)
process.argv[2] = "--help";
//----for later
// const yargs = require('yargs');
// var ver = yargs.version();
var { argv, exit } = require('process');
// var appStartMessage =
// `Multi platform Contact Sheet maker
// By Guillaume Descoteaux-Isabelle, 2020-2021
// version ${ver}
// ----------------------------------------`;
// //const { argv } = require('process');
// //const { hideBin } = require('yargs/helpers')
// const argv = yargs(process.argv)
//console.log(process.argv)
// .scriptName("gis-csm")
// .usage(appStartMessage)
// // .command('serve [port]', 'start the server', (yargs) => {
// // yargs
// // .positional('f', {
// // describe: 'port to bind on',
// // type:'string',
// // default: 5000
// // })
// // }, (argv) => {
// // if (argv.verbose) console.info(`start server on :${argv.port}`)
// // //serve(argv.port)
// // console.log("test");
// // console.info(`start server on :${argv.port}`)
// // })
// .option('file', {
// alias: 'f',
// type: 'string',
// description: 'Specify the file out'
// })
// .option('directory', {
// alias: 'd',
// type: 'boolean',
// default:false,
// description: 'Name the output using current Basedirname'
// }).usage(`gis-csm -d --label # Assuming this file in directory: vm_s01-v01_768x___285k.jpg
// # will extract 285 and add that instead of filename`)
// .option('verbose', {
// alias: 'v',
// default:false,
// type: 'boolean',
// description: 'Run with verbose logging'
// })
// .option('label', {
// alias: 'l',
// type: 'boolean',
// default:false,
// description: 'Label using last digit in filename (used for parsing inference result that contain checkpoint number)'
// })
// .argv;
//todo insert "-" as argv[2] if not that value
if (pipeMode)
{
var al = process.argv.length;// console.log(al);
if (al> 2)
{
var rearg =[];
var ii = 0;
for (let i = 0; i < process.argv.length; i++) {
const element = process.argv[i];
var tst = element;
if (i==2 && tst != "-") //insert "-" at pos 2 of the argv
{
rearg[ii] = "-";
ii++;
}
rearg[ii] = tst;
ii++;
}
process.argv = rearg;
}
else process.argv[2] = "-";
}
//console.log(process.argv)
//exit();
//-----------
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')
//if (d)console.log("------------------------")
//if (d)console.log( process.stdin);
//if (d)console.log("------------------------")
var appStartMessage =
`-------------------------
json2bash
By Guillaume Descoteaux-Isabelle, 2022
----------------------------------------`;
// const { exit } = require("node-process");
const helpExample = ` `;
argv =
yargs(hideBin(process.argv))
.scriptName("json2bash")
// .usage(appStartMessage + helpExample)
.usage('$0 <jsonFile> [objCsvArray] [fileout]', "run the thing", (yargs) => {
yargs.positional('jsonFile', {
describe: 'json File input',
type: 'string',
default: '-'
}),
yargs.positional('objCsvArray', {
describe: 'object to extract in the file as csv',
type: 'string',
default: '.'
}),
yargs.positional('fileout', {
describe: 'env file output',
type: 'string',
default: null
})
})
.epilogue('for more information, find our manual at https://github.com/GuillaumeIsabelle/json2bashenv#readme')
.option('var2Lower', {
default: false,
type: 'boolean',
alias: ['tolower', 'tl', 'toLowerCase', 'lc','l'],
description: 'Changes env name to lowercase'
})
.option('prefix', {
alias: ['p', 'px'],
default: false,
type: 'boolean',
description: 'prefix selected object output to var'
})
.option('all', {
alias: ['a'],
default: false,
type: 'boolean',
description: 'output all sub object'
})
.option('jsonx', {
alias: ['j','jx'],
default: false,
type: 'boolean',
description: 'output sub object as json'
})
.option('onlyselected', {
alias: ['o', 'os', 'oa', 'os', 'only'],
default: false,
type: 'boolean',
description: 'select only value of obj array as arg 2'
})
.option('verbose', {
alias: 'v',
default: false,
type: 'boolean',
description: 'Run with verbose logging'
})
.option('debug', {
alias: 'd',
default: false,
type: 'boolean',
description: 'Run with debug output'
})
.example("json2bash sample.json --tolower", "simple output")
.example("json2bash sample.json . outfile.env --tolower", "simple output to file (the dot signify we keep top level element)")
.example("json2bash samplelevel.json \"result\" --tolower", "extract the tag result")
.example("json2bash samplelevel.json \"result\" --tolower --oa --prefix", "extract the tag result only (no top level prop will output)")
.example("json2bash samplelevel.json \"result,stuff\" --tolower --prefix", "Extract the result and stuff object to lowercase and add their object name as prefix to variable")
.example("./json2bash samplesublevelon \"result\" -p;./json2bash samplesublevelon \"result\" -p -j |./json2bash \"meta\" -p -l -o", "Complex pipe extracting an object then one of its subobject pipe back to be extracted")
.argv;
//-----------
var { var2Lower, prefix, onlyselected, fileout, debug, verbose,all,jsonx } = argv;
var d = debug;
if (verbose)console.log(pipeMode?"Pipe mode active": "Normal mode");
//var fileout = argv.fileout? argv.fileout: null;
var noFileOut = fileout == null;
if (d) console.log(fileout, noFileOut);
var config = null;
const envListHelp = `
`;
if (!args || args.length == 0 ||args[0] == "--help")
{
console.log(`
HELP
json2bash myfile.json [--toLower]
--tolower = variable name
`);
}
else
{
if (d) console.log(argv);
try {
//Possible later support for .env preconf
try {
var tst = require('dotenv').config()
if (tst.parsed) {
config = new Object()
var { json2bashtofile,json2bashtofilepath } = tst.parsed;
var { json2bashtofile, json2bashtofilepath } = tst.parsed;
}
} catch (error) { }
var var2Lower = false;
try {
var filein = args[0];
if (args[1]) {
var tst = args[1];
if (tst.toLowerCase() =="--tolower") var2Lower=true;
if (tst.toLowerCase() =="--tolowercase") var2Lower=true;
if (tst =="--2lower") var2Lower=true;
if (tst =="--2lc") var2Lower=true;
if (tst =="-l") var2Lower=true;
if (tst =="--l") var2Lower=true;
}
let rawdata = fs.readFileSync(filein);
let jsonObject = JSON.parse(rawdata);
var d = false;
if (d) console.log(jsonObject.PublicIp)
if (argv.jsonFile != "-")
try {
var filein = argv.jsonFile //argv._[0];
let rawdata = fs.readFileSync(filein);
main(rawdata);
} catch (error) {
console.log("Error reading input file.")
console.log(error)
}
else try {
//read STDIn
const stdin = process.stdin;
let rawdata = '';
stdin.setEncoding('utf8');
stdin.on('data', function (chunk) {
rawdata += chunk;
});
var c = 0;
stdin.on('end', function () {
// console.log(c,":Hello " + rawdata);
main(rawdata);
c++;
});
stdin.on('error', console.error);
} catch (error) {
}
function main(rawdata) {
try {
var level = "";
let jsonObject = JSON.parse(rawdata);
// if (argv._[1]) level = argv._[1];
if (argv.objCsvArray) level = argv.objCsvArray;
var l = level.split(",");
if (d) console.log(l);
if (jsonx)
{
var o =new Object();
var i = 0;
l.forEach(el => {
Object.entries(jsonObject).forEach(entry => {
const [key, value] = entry;
if (el == key)
{
//output json
var json = JSON.stringify(value);
console.log(json);
o[key] =value;
i++;
}
});
});
// var json = JSON.stringify(o);
// console.log(json);
exit();
}
if (d) console.log(jsonObject.PublicIp)
var out = [];
var c = 0;
Object.entries(jsonObject).forEach(entry => {
const [key, value] = entry;
var outKey = key;
if (var2Lower) outKey = key.toLowerCase();
var t = typeof (value);
if (d) console.log(t);
// console.log(level);
// exit();
if (t != "object") {
if (d) console.log(key.trim(), "=", value.trim());
if (!onlyselected)
out[c] = "export " + outKey + "=\"" + value.trim() + "\"";
}
else {
if (d) console.log("Special parsing, we have an objcet")
l.forEach(kl => {
//console.log(kl);
if (key == kl || all) {
if (d) console.log(key, ":", kl);
var prefixKey = kl;
if (kl==".")prefixKey = key;
var o = parseObject2Bash(value, prefixKey, noFileOut,all);
if (o) {
if (verbose) console.log("Fileout activated")
o.forEach(oelem => {
out[c] = oelem;
c++;
});
}
}
});
}
c++;
});
if (d) console.log("-------------")
if (d) console.log(out)
var content = "";
out.forEach(element => {
// Output to console
if (noFileOut)
console.log(element)
// or create a content to write to file
else content += element + "\n";
});
if (!noFileOut) {
console.log("Writting file:", fileout);
try {
fs.writeFileSync(fileout, content);
//file written successfully
} catch (err) {
console.log("Error writing file:", fileout);
console.error(err)
}
}
} catch (error) {
console.log("Must specify a file as first args")
console.log(error)
}
}
/**
* Parse object 2 bash function
*
* @param {*} jsonObject
* @param {*} oLevelName
* @param {*} outputToStdOut
* @returns
*/
function parseObject2Bash(jsonObject, oLevelName = "", outputToStdOut = false,outputAll=false) {
if (d) console.log("olevel:", oLevelName);
if (d) console.log(jsonObject);
var i = 0;
var out = [];
var c = 0;
Object.entries(jsonObject).forEach(entry => {
const [key, value] = entry;
if (d) console.log(key.trim(),"=", value.trim());
if (d) console.log(key.trim(), "=", value.trim());
var outKey = key;
if (var2Lower) outKey = key.toLowerCase();
if (var2Lower) outKey = key.toLowerCase();
out[c] = "export " + outKey + "=\""+ value.trim()+ "\"";
c++;
var t = typeof (value);
if (d) console.log("f:", t);
var prefixVal = "";
if (prefix) prefixVal = oLevelName;
var envKeyName = prefixVal + outKey;
//value to output
if (t != "object") {
var v = "" + value;
out[i] = "export "
+ envKeyName
+ "=\""
+ v.replace(/(?:\r\n|\r|\n)/g, '\\n') + "\"";
}
else {
//We have an object
if(outputAll)
{
var o2 = parseObject2Bash(value,envKeyName,outputToStdOut,outputAll);
//add result to output
o2.forEach(e2 => {
out[i] = e2;
i++;
});
}
}
i++;
});
if (d) console.log("-------------")
if (d) console.log(out)
out.forEach(element => {
console.log(element)
});
} catch (error) {
console.log("Must specify a file as first args")
console.log(error)
if (outputToStdOut)
out.forEach(element => {
console.log(element)
});
else
return out;
}
function getObjArray(jsonObject)
{
Object.entries(jsonObject).forEach(entry => {
const [key, value] = entry;
var t = typeof (value);
var r = "";
//value to output
if (t == "object") {
r+= key
}
i++;
});
}
{
"name": "json2bash",
"version": "0.0.3",
"version": "0.2.0",
"description": "A CLI to export json object to bash env",
"main": "json2bash.js",
"scripts": {
"test": "node json2bash.js sample.json"
"test": "node json2bash.js sample.json",
"test2": "node json2bash.js samplelevel.json result"
},

@@ -9,0 +10,0 @@ "bin": {

@@ -16,2 +16,25 @@ # json2bashenv

json2bash sample.json --tolower
json2bash samplelevel.json --tolower
#simple output
#extract the tag result
json2bash samplelevel.json "result"
--tolower
#extract the tag result only
#(no top level prop will output)
json2bash samplelevel.json "result" --tolower --oa --prefix
#Extract the result and stuff object
#to lowercase and add their object name as prefix to variable
json2bash samplelevel.json "result,stuff" --tolower --prefix
```
## Complex Usage:
```sh
#Complex pipe extracting an object then one of its subobject pipe back to be extracted
./json2bash samplesublevelon \"result\" -p;./json2bash samplesublevelon \"result\" -p -j |./json2bash \"meta\" -p -l -o
```
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc