Skip to content

Instantly share code, notes, and snippets.

@commenthol
Created November 22, 2016 20:59
Show Gist options
  • Select an option

  • Save commenthol/bedf980947867d5c0c224f76e1e8e276 to your computer and use it in GitHub Desktop.

Select an option

Save commenthol/bedf980947867d5c0c224f76e1e8e276 to your computer and use it in GitHub Desktop.
print selected JSON data on console
#!/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