(no title)
johncs | 4 years ago
$ alias fooson="node --eval \"console.log(JSON.stringify(eval('(' + process.argv[1] + ')')))\""
$ fooson "{time: $(date +%s), dir: '$HOME'}"
{"time":1457195712,"dir":"/Users/jpm"}
It may be a bit nicer to place that JavaScript in your path as a node script instead of using an alias. #!/usr/bin/env node
console.log(JSON.stringify(eval('(' + process.argv[2] + ')')))
Since fooson's argument is being interpreted as JavaScript, you can access your environment through process.env. But you could make a slightly easier syntax in various ways. Like with this script: #!/usr/bin/env node
for(const [k, v] of Object.entries(process.env)) {
if (!global.hasOwnProperty(k)) {
global[k] = v;
}
}
console.log(JSON.stringify(eval('(' + process.argv[2] + ')')))
Now environmental variables can be access as if they were JS variables. This can let you handle strings with annoying quoting. $ export BAR="\"'''\"\""
$ fooson '{bar: BAR}'
{"bar": "\"'''\"\""}
If you wanted to do this without trusting your input so much, a JSON dialect where you can use single-quoted strings would get you pretty far. $ fooson "{'time': $(date +%s), 'dir': '$HOME'}"
{"time":1457195712,"dir":"/Users/jpm"}
If you taught the utility to expand env variables itself you'd be able to handle strings with mixed quoting as well. $ export BAR="\"'''\"\""
$ fooson '{"bar": "$BAR"}'
{"bar": "\"'''\"\""}
You'd only need small modifications to a JSON parser to make this work.
johncs|4 years ago