Skip to content

Instantly share code, notes, and snippets.

@geon
Created October 1, 2015 06:09
Show Gist options
  • Save geon/521a0a8f75c97decf642 to your computer and use it in GitHub Desktop.
Save geon/521a0a8f75c97decf642 to your computer and use it in GitHub Desktop.
Command line tool to extract values from a JSON file.
echo '{"foo1":123, "foo":{"bar":[1,2,3]}}' | ./json.js foo.bar.2
#!/usr/bin/env node
var keypath = process.argv[2];
var infile = process.argv[3];
if (infile) {
var input = require(process.argv[3]);
output(input);
} else {
var stdin = process.stdin,
inputChunks = [];
stdin.resume();
stdin.setEncoding('utf8');
stdin.on('data', function (chunk) {
inputChunks.push(chunk);
});
stdin.on('end', function () {
var input = JSON.parse(inputChunks.join(''));
output(input);
});
}
function output(parsedInput) {
var keys = keypath.split('.');
var value = parsedInput;
keys.forEach(function (key) {
value = value[key];
});
console.log(JSON.stringify(value, null, "\t"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment