Map, reduce, and filter JSON from the command line.
I've used jq for a long while to handle JSON from the command line. I've found the syntax hard to remember. I handle complicated things with jq infrequently. Causing the little learned to not stick.
I use JavaScript regularly. Why not just use JavaScript?
#!/usr/bin/env node
const p = require('process');
let text = '';
let json = null;
p.stdin.on('data', data => text += data.toString().trim());
p.stdin.on('end', () => {
try { json = JSON.parse(text); } catch {}
p.argv.slice(2).forEach(arg => console.log(eval(arg)));
});
This is a NodeJS script that should be placed in a bin
folder and set as executable, chmod +x
.
Example usage:
$ curl -sS https://unpkg.com/angular@1.8.2/package.json | ~/bin/js 'var ident = json.keywords[0]; ident.charAt(0).toUpperCase() + ident.slice(1) + " is a client side web framework."'
Angular is a client side web framework.
All of NodeJS is available to the tiny script. Two global are provided for you text
and json
, json
will be null
if stdin
was not valid JSON.
Additonally, if you're a fan of lodash, this js version includes lodash in top-level scope. E.G. functions such as first
become availabe.
curl -sS https://unpkg.com/angular@1.8.2/package.json | ~/bin/js 'first(json.keywords)'
EOF