Created
November 22, 2016 20:59
-
-
Save commenthol/bedf980947867d5c0c224f76e1e8e276 to your computer and use it in GitHub Desktop.
print selected JSON data on console
This file contains hidden or 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 | |
| /** | |
| * print selected JSON data on console | |
| * | |
| * using files | |
| * | |
| * curl https://registry.npmjs.com/mergee > /tmp/j | |
| * json /tmp/j versions 0.2.3 name | |
| * | |
| * piping from stdin | |
| * | |
| * curl https://registry.npmjs.com/mergee | json -- versions 0.2.3 name | |
| * | |
| * @license MIT | |
| */ | |
| var path = require('path') | |
| var fs = require('fs') | |
| var args = process.argv.slice(2) | |
| main() | |
| function _get (obj, keys) { | |
| var tmp = obj | |
| if (keys) { | |
| for (var i = 0; i < keys.length; i++) { | |
| var key = keys[i] | |
| if (tmp && tmp.hasOwnProperty(key)) { | |
| tmp = tmp[key] | |
| } | |
| else { | |
| return undefined | |
| } | |
| } | |
| } | |
| return tmp | |
| } | |
| function out (str) { | |
| if (args.length === 1) { | |
| args = args[0].split('.') | |
| } | |
| var data = _get(JSON.parse(str), args) | |
| console.log(JSON.stringify(data, null, 2)) | |
| } | |
| function main () { | |
| var str = '' | |
| if (args.length && args[0] !== '--') { | |
| var file = path.resolve(process.cwd(), args.shift()) | |
| var str = fs.readFileSync(file, 'utf8') | |
| out(str) | |
| } else { | |
| args.shift() | |
| process.stdin.setEncoding('utf8'); | |
| process.stdin.on('readable', () => { | |
| var chunk = process.stdin.read() | |
| if (chunk !== null) str += chunk | |
| }) | |
| process.stdin.on('end', () => { | |
| out(str) | |
| }) | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment